Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rubocop guard clause dilemma - unnecessary if else VS line too long guard clause

Tags:

ruby

rubocop

I have this piece of code where I have a raise statement with a guard clause:

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 to normal if else case as 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.

What to do in such case? Both are raising errors. Any other alternative?

like image 201
Lokesh Avatar asked Nov 06 '16 05:11

Lokesh


2 Answers

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
like image 82
Matt Schuchard Avatar answered Sep 29 '22 16:09

Matt Schuchard


Give this a try:

This will reduce the line length while raising the argument error

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
like image 28
Deepak Mahakale Avatar answered Sep 29 '22 15:09

Deepak Mahakale