Rubocop: Improve "normal if-statement" message if guard improvement can be detected

Created on 24 Mar 2017  路  1Comment  路  Source: rubocop-hq/rubocop

Steps to reproduce the problem

I ran rubocop over these lines:

def if_statement
  a
  c(
    1,
    2,
    3
  ) if condition?
end

It suggests:

Favor a normal if-statement over a modifier clause in a multiline statement.

Ok, fair enough. So I changed it to what Rubocop suggested:

def if_statement
  a
  if condition?
    c(
      1,
      2,
      3
    )
  end
end

But now Rubocop complains again:

 Use a guard clause instead of wrapping the code inside a conditional expression.

The documentation for a guard clause didn't initially seem relevant to my case, because I'm not doing any work if the clause fails.

What Rubocop actually wanted, which may be obvious to you (but it wasn't to me) is:

def if_statement
  return a unless condition?

  c(
    1,
    2,
    3
  )
end

Expected behavior

It would have been nice if possible for Rubocop to initially tell me to use a guard, not a wrapping if, if that's detectable. A bonus would be to update the documentation to make this case more clear, but I'm not sure what that update would entail.

RuboCop version

0.47.1 (using Parser 2.4.0.0, running on ruby 2.1.5 x86_64-darwin14.0)

>All comments

It would have been nice if possible for Rubocop to initially tell me to use a guard, not a wrapping if, if that's detectable. A bonus would be to update the documentation to make this case more clear, but I'm not sure what that update would entail.

Those are two different checks, so we can't really implement what your suggesting unless we duplicate some logic, which I'd rather us not do.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bbatsov picture bbatsov  路  3Comments

benoittgt picture benoittgt  路  3Comments

bbugh picture bbugh  路  3Comments

tedPen picture tedPen  路  3Comments

deivid-rodriguez picture deivid-rodriguez  路  3Comments