Should you use "this.variablename" or just "variablename" to reference a member variable in a method?
You can use whichever you want in most cases. If your method parameter has the same name then you'll need to use this to distinguish the instance variable. Be consistent!
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.
I only use this. in two circumstances:
- To disambiguate between the field and a local of the same name, for example in a setter;
- When my method has a
thatparameter, becausethisandthatmake for nice readable code.
Just the variable name is ok & to use the parameter variable use "this".
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).