Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a cop that checks for initializer returns #4153

Closed
Drenmi opened this issue Mar 22, 2017 · 2 comments
Closed

Add a cop that checks for initializer returns #4153

Drenmi opened this issue Mar 22, 2017 · 2 comments

Comments

@Drenmi
Copy link
Collaborator

Drenmi commented Mar 22, 2017

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)
@mikegee
Copy link
Contributor

mikegee commented Mar 22, 2017

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

@harold-s
Copy link

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

pocke added a commit to pocke/rubocop that referenced this issue Jun 5, 2017
In `initialize` and setter methods, returned value is ignored(See rubocop#4153).

```ruby
def initialize
  42 # This value is ignored.
end
```

However, `Lint/Void` cop doesn't add an offense for the above code.

This change makes to add an offense for the code.
bbatsov pushed a commit that referenced this issue Jun 5, 2017
In `initialize` and setter methods, returned value is ignored(See #4153).

```ruby
def initialize
  42 # This value is ignored.
end
```

However, `Lint/Void` cop doesn't add an offense for the above code.

This change makes to add an offense for the code.
pocke pushed a commit to pocke/rubocop that referenced this issue Jun 5, 2017
@bbatsov bbatsov closed this as completed in bc16f89 Jun 5, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants