2016-11-06 43 views
2

我有这样的一段代码,我有保护条款加薪声明:Rubocop后卫条款的困境 - 不必要的,如果别的VS行太长后卫条款

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. 

在这种情况下该做什么?两者都在提出错误。任何其他的选择?同时提高参数错误

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 
+0

你不必盲目追随一切rubocop说。您可以在'.rubocop.yml'中禁用GuardClause样式检查。 –

+0

您也可以使用#rubocop禁用单个项目:disable和#rubocop:enable – Joe

回答

4

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 

它是由

1

这给一试给你,如果你想走那条路。无论哪种方式,Rubocop还建议:

def validate_index(index) 

如果你走你的原来的路线,而忽略Rubocop,你也真的应该考虑改变你的if !=一个unless

unless size == index.size 
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