I Don't Like this Any More

by Eric M. Burke

I used to be in the habit prefixing object field references with "this". I'd write code like this:

class Person {
private String firstName;

public String getFirstName() {
return this.firstName;
}
}




It seems harmless enough. But things get out of hand rather quickly:

class Person {
private String firstName;
private String lastName;
private String middleName;

public String getFullName() {
return this.firstName + " "
+ this.middleName + " "
+ this.lastName;

}
}


As you sprinkle in more and more "this" references, the code becomes increasingly cluttered. I found myself asking:

Does this really help?


I think the code is more readable when written like this:

class Person {
private String firstName;
private String lastName;
private String middleName;

public String getFullName() {
return firstName + " "
+ middleName + " "
+ lastName;

}
}



Just sit back and look at the two code examples. Which is more visually appealing? Which one looks cleaner? Do the "this" keywords add clarity, or make the screen busier?

Yeah, But...


Some people will disagree with me on "this" topic. They will argue that any field adorned with "this" is obviously an object field, while other fields are obviously local variables. I used to fall into this camp. I got into the habit of writing code in this style and prefixed all fields with "this" even when the code was painfully obvious without the extra clutter.


Can anybody honestly argue that this method is confusing?

public int getAge() {
return age;
}

age is obviously not a local variable. Adding the "this." prefix only adds clutter, making your code less readable. Heck, good IDEs like IntelliJ IDEA even highlight object fields a different color, further removing the need for "this".

DRY


Don't Repeat Yourself. If you really insist upon adorning your object fields with some token, I will argue that "this." is a horrible way of doing so. Instead, consider prefixing your field with a consistent name or character. I'm not crazy about prefixes, but they beat "this" because of the DRY principle. For example:

public class Person {
// show both ways...
private String _firstName;
private String lastName;

public String getFirstName() {
return _firstName;
}

public String getLastName() {
return this.lastName;
}

public String getFullName() {
// oops...forgot to prefix with "this" on our lastName
return _firstName + lastName;
}
}


Did you see what happened? In the getFullName() method, I forgot to prefix the lastName with "this". The code works fine, but this violates the DRY principle. If you adopt the "I shall prefix all fields with 'this'" mantra, you are advocating reliance upon humans to manually remember to prefix all object fields with "this" over and over again. Relying upon humans to manually copy a prefix over and over is a recipe for inconsistency because you are repeating yourself all over the place.


Adopting a prefix like "m_" or "_" is preferable to "this" because the compiler ensures consistency. It does not rely on human programmers to remember to repeat the "this" prefix over and over.


Let me repeat: Do not Repeat Yourself.


Like I said a few paragraphs back, I don't like this approach, however it is better than the "this" convention. I'm just presenting it as an option.

Your Code is Too Complicated



What if you have some really complicated method that uses a combination of local variables and object fields? Don't you need to prefix object fields with "this" to avoid ambiguity?


no.


I don't buy the argument. To me, it sounds like this:


"This method is too complicated to understand. I'm looking at the code and I cannot tell which field is a local variable and which field is an object field. My solution is to add MORE code by prefixing all object fields with 'this.', making the code even more cluttered."

I propose another solution: refactor the code until it is simple enough to understand without the "this" adornments.

On a Related Topic...


Study up on XP and see what the experts have to say about comments. If code is too hard to understand, adding more comments should not be your first reaction. Instead, think really hard about finding ways to simplify your code so the comments are not necessary.

Be Open Minded


Coding conventions are a religious issue, to be sure. I myself used to believe in the "this" convention as you'll see if you read any of my books. I must confess that it was difficult to give up the habit, and I still find myself habitually typing "this" occasionally.


My advice to anyone is to be open minded about your coding habits. It is really easy to fall into the trap of immediately disliking new ideas because they are foreign to you. If you are in the habit of prefixing your code with "this", code that does not follow the convention will look ugly to you at first glance. It did to me. All I can say is that I have changed my outlook and I like the simpler style better. You might also if you give it a chance.

Conclusion



  1. Absolutely trivial methods do not need the "this" prefix. Surely you will agree that this is simple:
    public int getAge() {
    return age;
    }


  2. The "this" convention violates the DRY principle. It forces you to manually replicate "this" all over the place. If you forget to follow the convention, the code works the same and the compiler issues no warning.


  3. If your code is too hard to understand, try to simplify it rather than to adorn it with "this" prefixes all over the place.


  4. If you really need to differentiate local variables from object fields, consider prefixing your object fields with "_" or some other character. You can always refactor your code later - using IDEA or a similar refactoring tool of course - if you decide you don't like the convention!


  5. Don't blindly follow conventions for the sake of following conventions. Follow conventions because they improve your code. If the coding convention encourages repetition, increases clutter, and relies upon human consistency to be effective, maybe the convention is flawed.





Do "this" prefixes improve clarity or make code more complicated?


22 Comments

anonymous2
2003-06-22 16:25:54
Re: I Don't Like "this" Any More
Amen!
revdiablo
2003-06-22 17:59:42
cargo cult
Don't blindly follow conventions for the sake of following conventions. Follow conventions because they improve your code. If the coding convention encourages repetition, increases clutter, and relies upon human consistency to be effective, maybe the convention is flawed.


It might be interesting to note that this is the essence of avoiding so-called cargo cult programming. All in all, very good advice. :)

anonymous2
2003-06-22 19:49:50
Autocomplete footprints, Python
Thanks for the explanation. I've seen 'this.' used a lot where the original coder was accessing the auto-complete tool for a list of local variables.
anonymous2
2003-06-23 06:11:15
The name of the game is readability
I only use this when I feel that it improves readability. I use this in mutators like so


public void setFirstName(String first) {
this.first = first;
}


But I would not use in the corresponding accessor. Above all I donít use m_ or _ because it gets in the way of reading the code (that and I am java programmer, not a C or C++)!!


bashyal
2003-06-23 07:02:16
Using accessors
Oops.. double post
bashyal
2003-06-23 07:05:25
Using accessors
Why not use accessors to create properties, except for the instance variables themselves.


public String getFirstName(){
return firstName;
}


....


public String getFullName() {
return getFirstName() + " "
+ getMiddleName() + " "
+ getLastName();
}

anonymous2
2003-06-23 07:19:55
Another reason not to use this.
The following code will still compile even when the parameter is removed:


private int count;


public void doSomething(String tag, int count) {
this.count = count;
}

anonymous2
2003-06-23 07:55:18
What's really worse is VB.NET
VB.Net programmers should be so lucky as to have a "this." Instead they are forced to use me.


return me.age

anonymous2
2003-06-23 11:22:19
I stopped using 'this' too
Now all member variables are myFirstName or myLastName (or similar). That way I can still have coherent method parameter lists.


Public Name(String firstName, String lastName) {
myFirstName = firstName;
myLastName = lastName;
}

anonymous2
2003-06-23 13:54:09
Prefixes
I must confess to being a 'this' fanatic until relatively recently, where I switched to using prefixes using the scheme as suggested by Bob Martin (I think, correct me if I'm wrong) where members are prefixed by 'my', parameters are prefixed with 'the' and class statics are prefixed with 'their', e.g.:


class Person {
private String myFirstName;
private String myLastName;
private String myMiddleName;


public String getFullName() {
return myFirstName + " "
+ myMiddleName + " "
+ myLastName;
}


public void setFirstName(String theFirstName) {
myFirstName = theFirstName;
}

public static List theirCachedEntries;


}


I find it improves readability and the use of 'my'/'their' reinforces the sense of objectification(!), prompting people to question if that variable really 'belongs' to the object or class. YMMV.

anonymous2
2003-06-24 02:13:30
I use "_"
I use the "_" prefix for fields. I used "this" first because the automatic code generator of Netbeans forces you to do so, but I like to immediately distinguish local variables from fields. I don't like to adopt more verbose prefixes, like "my" or "m_" because this introduces redundancy: it's like the "www" in front of every web address (imagine if everybody's first name were John...).
blackcloud
2003-06-24 07:10:08
I'm lazy, and the use of "_"
The only time I use "this" when it's not required is when I want the IDE (Forte/Sun ONE) to pop up a list member fields and functions. Sometimes I back it out after making my selection, sometimes not.


For the person who commented on using "_", you're really comparing apples and oranges. "_" just decorates the name and doesn't serve any other function, while "this" is the object's self-reference. I will say that I use "_" to preface all private class members and find its use makes the code more readable.

anonymous2
2003-06-24 23:16:01
Isn't prefixing common currency already?
Dear fellows,
I'm slightly surprised indeed, I daresay.
Always thought prefixing (using whatsoever character(s) - with us it's a leading "f" followed by the name of the field, first letter capitalized; I suppose, the underscore stuff is more Microsoft's MFC habit) is common currency already..
Instead, I understand there are still those "this"-people out there ;-)


Regards,
Matthias Paul Scholz

anonymous2
2003-06-24 23:27:56
color code it
IDEA will syntax highlight the member variables differently than the local variables. It's the safest and cleanest way.
anonymous2
2003-06-26 06:46:33
Prefixes aren't necessary
In the situation described in "Another reason not to use this." a good compiler/IDE would normally issue a warning. Eclipse does.


It seems that really using prefixes is a kind of optional and not very useful practice. They clutter the code. One can stick with readable variable names, and only use "this." when assigning a value.


No doubt that using "this." everywhere is overkill and generally is a bad habit.

anonymous2
2003-06-26 08:27:09
Doubts
I used to use the "start with _" convention for members when I programmed in C++, but doesn't that either screw up the the Java Beans method naming model (or give you ugly getter and setter names (_foo paired with set_foo() and get_foo() instead of foo paired with setFoo() and getFoo())?


You don't HAVE to name your setters and getters exactly like the field name, as your examples show, but it does complicate things when using tools that autogenerate getters and setters and when relying on reflection.


And starting members names with things like "m_" is ugly and distracting from the real meaning, almost as bad as Hungarian notation.

anonymous2
2003-06-26 17:47:08
Doubts
No, beans properties are defined entirely by the getter/setter names, not the member names.


String getName() {
return mName;
}


is the getter for property 'name', regardless of the spelling of the member variable.

coyner_b
2003-07-03 07:48:38
I Took The Challenge...
Eric and I have had numerous discussions regarding "this". He challenged me, on numerous occasions, to stop using it, but I refused. I never had any good reasons why I liked "this", though. Therefore I gave myself about week or so to try and not write code using "this.". I am very pleased to announce that I am now on Eric's side (along with many others). I cannot stand seeing "this.", and when I do see it I have to remove it. It's amazing what can happen in a few days. I challenge everyone to try it.


Brian

anonymous2
2003-07-23 10:11:17
re: I Don't Like "this" Any More
Excellent article and a good read.
anonymous2
2003-07-25 02:55:37
The name of the game is readability
I try to only use "this" in constructors or setters to allows Contsructor parameters to have the sames semantic meaning.
There's no need to pepper code with "this." just for the hell of it, neither is there a need to rely on prefixes. I personnaly find prefixes far uglier than "this.", even if a variable name is longer than a prefixed Equivalent i.e. Gobutton instead of btnGo, simpley because prefixes get so out of hand.
anonymous2
2003-07-25 02:56:06
The name of the game is readability
I try to only use "this" in constructors or setters to allows Contsructor parameters to have the sames semantic meaning.
There's no need to pepper code with "this." just for the hell of it, neither is there a need to rely on prefixes. I personnaly find prefixes far uglier than "this.", even if a variable name is longer than a prefixed Equivalent i.e. Gobutton instead of btnGo, simply because prefixes get so out of hand.
Elling
2005-01-21 15:58:48
The "this" keyword and unambiguity
"Can anybody honestly argue that this method is confusing?



public int getAge() {
return age;
}
"


No, I can't argue that it's confusing. But if you have the following code it might be confusing:


public int getAge() {
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla
bla-bla-bla
bla-bla


return age;
}


If you have a function that's pretty long, then you'll find yourself skipping back up in the code to see if a referenced variable is a local variable or an object variable. Or at least you'll tend to do so if you're reading someone elses code which you're not familiar with.


So, I guess you COULD do as you propose and vary the technique according to whether the code makes sense without the "this" keyword or not.


But if you do that, then you also loose the GOOD effect of using the "this" operator, because each time you see a referenced variable without the this keyword in front of it, you'll come to wonder if it REALLY is a local variable, or if the coder just left it out because he thought the ownership of it was obvious.


So, even though you might get some code that "looks neater" out of it, I still prefer using the "this" keyword because it gives you unambiguity in your code. And in my opinion unambiguity is MUCH more important in programming than neatness.