Rubocop: Add a cop that checks for initializer returns

Created on 22 Mar 2017  路  2Comments  路  Source: rubocop-hq/rubocop

I am seeing more and more code like this:

def initialize
  foo
  return :qux if bar?
  baz
end

I don't think it's very useful to return from an initializer, or at least I have never had a need to do so before. Even if there are cases where that would make sense, it is not possible to use a return value from an initializer.

I suggest a cop that marks returns from initializer methods as offenses or, alternatively (if someone can provide a strong rationale for still doing that) marks code that tries to return an explicit value from an initilaizer.


Expected behavior

RuboCop registers an offense.

Actual behavior

RuboCop doesn't register an offense.

Steps to reproduce the problem

Run bundle exec rubocop on:

def initialize
  foo
  return :qux if bar?
  baz
end

RuboCop version

Include the output of rubocop -V. Here's an example:

$ rubocop -V
0.47.1 (using Parser 2.3.3.1, running on ruby 2.3.3 x86_64-darwin15)
feature request

Most helpful comment

This reminded me that the return value from setter methods is ignored. We could make a cop for that too.

pry> class A
pry*   def foo=(bar)
pry*     return 42
pry*   end
pry* end
pry> a = A.new
pry> a.foo = :some_value
:some_value

All 2 comments

This reminded me that the return value from setter methods is ignored. We could make a cop for that too.

pry> class A
pry*   def foo=(bar)
pry*     return 42
pry*   end
pry* end
pry> a = A.new
pry> a.foo = :some_value
:some_value

ConfigurableEnforcedStyle uses a return in the detected_style= setter method.
Will fix my PR later to modify this file.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bbatsov picture bbatsov  路  3Comments

kirrmann picture kirrmann  路  3Comments

ecbrodie picture ecbrodie  路  3Comments

bquorning picture bquorning  路  3Comments

NobodysNightmare picture NobodysNightmare  路  3Comments