2016-11-06 40 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