我有这段代码,我有一个带有保护条款的加注声明:
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
对此,rubocop给出了进攻:
Style/MultilineIfModifier: Favor a normal if-statement over a modifier clause in a multiline statement.
我将我的代码修改为正常,如果是这样的情况:
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
但是现在它给了这个冒犯:
Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.
在这种情况下该怎么办?两者都在提高错误。还有其他选择吗?
答案 0 :(得分:9)
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
如果你想走这条路,那取决于你。无论哪种方式,Rubocop也建议:
def validate_index(index)
如果你走原路并忽略Rubocop,你也应该考虑将if !=
改为unless
:
unless size == index.size
答案 1 :(得分:2)
尝试一下:
这会在提高参数错误时缩短行长度
def validate_index index
# Change to SizeError
error_message =
"Size of index (#{index.size}) does not matches size of vector (#{size})"
raise ArgumentError, error_message if size != index.size
end
答案 2 :(得分:1)
你认为与布尔表达式连接是什么意思?,如:
def validate_index index
# Change to SizeError
size != index.size &&
raise ArgumentError, "Size of index (#{index.size}) does not matches"\
"size of vector (#{size})"
end