Reputation: 79756
Should you use "this.variablename" or just "variablename" to reference a member variable in a method?
Upvotes: 7
Views: 1257
Reputation: 1617
I'm a fan of using the language features when programming in a language. Thus, I would recommend against using "this." on an instance variable unless required to distinguish it from a method parameter that is colliding on the same name.
Upvotes: 0
Reputation: 51150
You can use whichever you want in most cases. If your method parameter or local variable has the same name then you'll need to use this
to distinguish the instance variable. Be consistent!
Upvotes: 5
Reputation: 46836
Use this.
- it helps other programmers to visually identify the usage of member fields, and makes refactoring easier (e.g. when considering moving of a method to another class).
Upvotes: 1
Reputation: 9942
Just the variable name is ok & to use the parameter variable use "this".
Upvotes: 0
Reputation: 40356
I only use this.
in two circumstances:
that
parameter, because this
and that
make for nice readable code.Upvotes: 2
Reputation: 88385
You can do either, it's just a matter of taste, but I've seen a lot of Java code use "this." because the arguments to the method are named the same as the member field a lot of times.
You could argue that using "this." also helps readability, because you immediately know it's a member, but you could also argue that "this." hurts readability, because it's just an extraneous word.
Upvotes: 4