我有这段代码,我有一个带有保护条款的加注声明:
def validate_index index
# Change to SizeError
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})" if size != index.size
end
Run Code Online (Sandbox Code Playgroud)
在这方面,rubocop给出了进攻:
Style/MultilineIfModifier: Favor a normal if-statement over a modifier clause in a multiline statement.
Run Code Online (Sandbox Code Playgroud)
我将我的代码修改为正常if else case如下:
def validate_index index
# Change to SizeError
if size != index.size
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})"
end
end
Run Code Online (Sandbox Code Playgroud)
但是现在它给了这个冒犯:
Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
Run Code Online (Sandbox Code Playgroud)
在这种情况下该怎么办?两者都在提高错误.还有其他选择吗?
Mat*_*ard 10
Rubocop希望你这样写:
def validate_index index
# Change to SizeError
return if size == index.size
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})"
end
Run Code Online (Sandbox Code Playgroud)
如果你想走这条路,那取决于你.无论哪种方式,Rubocop也建议:
def validate_index(index)
Run Code Online (Sandbox Code Playgroud)
如果你走原路并忽略Rubocop,你也应该考虑将你if !=改为unless:
unless size == index.size
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2297 次 |
| 最近记录: |