Lokesh Lokesh - 29 days ago 26
Ruby Question

Rubocop guard clause dilemma

I have this piece of code:

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


On this, rubocop gives the offence:

Style/MultilineIfModifier: Favor a normal if-statement over a modifier clause in a multiline statement.


I modified my code to this:

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


But now it gives this offence:

Style/GuardClause: Use a guard clause instead of wrapping the code inside a conditional expression.


Am I doing something wrong or is this a bug?

Answer

Rubocop wants you to write it like this:

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

It is up to you if you want to go that route. Either way, Rubocop is also recommending:

def validate_index(index)

If you go your original route and ignore Rubocop, you should also really consider changing your if != to an unless:

unless size == index.size
Comments