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.
The only place I use this is in constructors in classes where some/most of the fields of the class can be supplied by the constructor. I use this rather than using short names for the method signature, it just seems more consistent than abbreviating.
For example in a class "Rational"
Rather than doing
I do this.
That way callers know more about what the constructors parameters are for.
I most often see people do this because it triggers the intellisense. I personally prefer to leave off the "this." because it creates more code without any value.
I think there's nothing wrong if you put in this before the property name. This helps disambiguate the property from local variables should you have any declared with the same name (which may happen in a constructor when you initialize properties).
It doesn't affect performance, it doesn't create any problems for readability (if at all it makes reading easier).
So I don't think we need to worry about this. Let the programmers make their own choice.
Sometimes it is necessary to disambiguate:
At other times, it's just a stylistic thing. On the whole, I try to avoid
this.blah
wherever possible as it is more verbose. In case you're wondering, the resultant bytecode is exactly the same.I try to use 'this.whatever' when writing large chunks of code, because it was easier to figure out what was being referenced. When reading large chunks of code written by other people, at certain points I would often get confused as to whether they were referencing instance variables or local variables.
They are perhaps a Python programmer and get tortured/lost/confused without an explicit this.