When referencing class variables, why do people prepend it with this
? I'm not talking about the case when this
is used to disambiguate from method parameters, but rather when it seems unnecessary.
Example:
public class Person {
private String name;
public String toString() {
return this.name;
}
}
In toString
, why not just reference name
as name
?
return name;
What does this.name
buy?
Here's a stackoverflow question whose code has this
pre-pending.
It does nothing at the language level. But it does give immediate indication to someone reading the code about the scope of the variable, which improves understanding of the code.
Something else to keep in mind is the language itself. You didn't mention Java specifically (though I'm assuming you didn't really have anything else in mind, so this comment is more FYI), but as the previous posters have mentioned already it is an excellent way of making code self-documenting to prevent mix-ups down the road when someone else starts modifying your code base.
If you take PHP, though, the use of
$this
is typically required when referencing class variables. With differing rules between languages, it is often easiest to stick with the pattern that is common between them, a pattern which just so happens to be a very solid coding style throughout. It's easier for me to simply prependthis
to everything than try to remember what language requires it and what language simply "prefers" it.It helps you identify member variables at a glance..
the ToString() above is too tiny to illustrate this.
Suppose you have a screenful size method. You calculate, assign, swap a mix of local and instance variables.
this.memberVar
orthis.PropertyName
helps you keep track of where you are modifying instance state via field assignments or property setters.A slight aside, but it may be worth noting that the "Clean Up" tool in Eclipse can be set to automatically add/remove this. to member accesses according to preference.
"Java / Code Style / Clean Up" in the preferences dialogue.
In .NET world the Microsoft StyleCop tool also has a rule called "Prefix Local Calls With This":
My suggestion is to choose a convention (use this. or not) and stick with that.