Rubocop 保护子句困境 - 不必要 if else VS 行太长保护子句
Rubocop guard clause dilemma - unnecessary if else VS line too long guard clause
我有一段代码,其中有一个带保护子句的 raise 语句:
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.
我将我的代码修改为正常 if else 情况如下:
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.
遇到这种情况怎么办?两者都在引发错误。还有其他选择吗?
试一试:
这将减少行长度,同时增加参数错误
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
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
你觉得用布尔表达式连接起来怎么样?,比如:
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
我有一段代码,其中有一个带保护子句的 raise 语句:
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.
我将我的代码修改为正常 if else 情况如下:
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.
遇到这种情况怎么办?两者都在引发错误。还有其他选择吗?
试一试:
这将减少行长度,同时增加参数错误
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
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
你觉得用布尔表达式连接起来怎么样?,比如:
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