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

'Useless assignment' reported when setting atttribute on method parameter #438

Closed
dirkbolte opened this issue Aug 16, 2013 · 5 comments · Fixed by #443
Closed

'Useless assignment' reported when setting atttribute on method parameter #438

dirkbolte opened this issue Aug 16, 2013 · 5 comments · Fixed by #443

Comments

@dirkbolte
Copy link
Contributor

The following code results in a warning: Useless assignment to local variable test_class. for test_class.member = value:

# encoding: UTF-8
# TestClass
class TestClass
  attr_accessor :member
end

def add_to_hash(test_class, value)
  test_class.member = value
end
tc = TestClass.new
add_to_hash(tc, 'a')
puts tc.member
@bbatsov
Copy link
Collaborator

bbatsov commented Aug 16, 2013

Parameters are treated as local vars by the parser and assignments to local vars as the result of a functions generally make no sense. Assignment to parameters is considered extremely bad style anyways...

@dirkbolte
Copy link
Contributor Author

I completely agree on style. Nevertheless the code actually does something and has an effect outside of that method call.

@bbatsov
Copy link
Collaborator

bbatsov commented Aug 16, 2013

The problem is that we cannot simply allow assignments to params, because of code like this:

def add_to_hash(test_class, value)
  test_class = NewClass.new
  # there is a param test_class, but this is no longer it
  test_class.member = value
end

Checking for assignments to all the params might be one solution (not sure how robust, though) - if there are no, we assume this is still a param and it's OK to assign to it.

@yujinakayama Would you volunteer to fix this issue? :-)

@yujinakayama
Copy link
Collaborator

OK 👍

@jonas054
Copy link
Collaborator

Then there are a number of special cases that make the assignment "not useless". I don't know if they're too far-fetched or if we should worry about them.

  • Aliasing such as @tc = test_class or store_reference(test_class)
  • If the TestClass#member= method is not just assigning an attribute, but has side effects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants