views:

1065

answers:

16

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.

+2  A: 

Apart from the disambiguation with method parameters, it buys you nothing. Maybe clarity/readability but that really depends on your style.

Cogsy
+9  A: 

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.

Joseph Daigle
I would've said the same thing. It increases understandability, puts things into their correct context thus stopping ambiguity. The eventual bytecode would be the same anyway I believe.
Kezzer
I don't think it improves understanding. IMO, of course. That might be the case with few, I don't know.
Adeel Ansari
I think that's subjective then, and relative to the individual.
Kezzer
It's subject to a point. If it's considering a coding standard on your project, then it might not be. But if you follow the convention it does indicate the scope of the variable. Additionally, static variables on the class should always use the classname in reference.
Joseph Daigle
It clutters the code, you should be using an IDE that color-highlights local variables versus instance variables so it is very clear which is which. this. should only be used when there is a name collision, but besides getters and setters, there shouldn't be name collisions in good code.
MetroidFan2002
Code clutter is subjective. But regardless, you probably don't want to rely on "color" to differentiate the scope of code. That limits things significantly. What if I'm a colorbind programmer?
Joseph Daigle
+41  A: 
  1. Defensive programming (in case someone editing the code later adds a parameter or local with a conflicting name
  2. Make the code "self documenting," more obvious
Doug Currie
+29  A: 

Sometimes it is necessary to disambiguate:

public void setFoo(Bar foo) {
    this.foo = foo;
}

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.

Daniel Spiewak
+2  A: 

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 or this.PropertyName helps you keep track of where you are modifying instance state via field assignments or property setters.

Gishu
+1  A: 

They are perhaps a Python programmer and get tortured/lost/confused without an explicit this.

Ali A
A: 

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 prepend this to everything than try to remember what language requires it and what language simply "prefers" it.

Magsol
+8  A: 

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.

jwanagel
A: 

"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".

duncan
A: 

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.

Patrick Lin
+1  A: 

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.

Cyril Gupta
+4  A: 

In .NET world the Microsoft StyleCop tool also has a rule called "Prefix Local Calls With This":

A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’. An exception to this rule occurs when there is a local override of a base class member, and the code intends to call the base class member directly, bypassing the local override. In this case the call can be prefixed with ‘base.’ rather than ‘this.’.

By default, StyleCop disallows the use of underscores or m_ to mark local class fields, in favor of the ‘this.’ prefix. The advantage of using ‘this.’ is that it applies equally to all element types including methods, properties, etc., and not just fields, making all calls to class members instantly recognizable, regardless of which editor is being used to view the code. Another advantage is that it creates a quick, recognizable differentiation between instance members and static members, which are not be prefixed.

A final advantage of using the ‘this.’ prefix is that typing this. will cause Visual Studio to show the IntelliSense popup, making it quick and easy for the developer to choose the class member to call.

My suggestion is to choose a convention (use this. or not) and stick with that.

huseyint
A: 

The code is simplier reading. Another good practice, in my opinion, is calling the getXXX() in toString() too (instead then this.XXX), beacuse the getXXX() 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.

alepuzio
+2  A: 

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.

Cheekysoft
+1  A: 

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.

duffymo
A: 

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

class Rational
{
    int denominator;
    int numerator;

    public Rational(int d, int n)
    {
        denominator = d;
        numerator = n;
    }
}

I do this.

class Rational
{
    int denominator;
    int numerator;

    public Rational(int denominator, int numerator)
    {
        this.denominator = denominator;
        this.numerator = numerator;
    }
}

That way callers know more about what the constructors parameters are for.

Tony Peterson