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.
Same reason why some people like to prepend private data members with "m_" or name interfaces "IFoo". They believe it increases readability and clarity. Whether or not you agree with conventions like these is a matter of taste.
"this" prevents confusion with instance variables with the same name in the parent class/es.
It's pretty much the complement to prepending with "super".
The code is simplier reading. Another good practice, in my opinion, is calling the
getXXX()
intoString()
too (instead thenthis.XXX
), beacuse thegetXXX()
can have an important logic.I think that use the name of attribute without this is'nt a good idea for the maintenance of the application.
Apart from the disambiguation with method parameters, it buys you nothing. Maybe clarity/readability but that really depends on your style.