Using an explicit this to refer to an instance variable is a bad habit. I'll start with an example I recently saw:

public class Person
{
    private String name;
    private String address;

    public MyClass( String name, String address )    {
        this.name = name;
        this.address = address;
    }
}
This is something you see every day, right?

Now, what happened is that address was removed from the class constructor. Result was:

public class Person
{
    private String name;
    private String address;

    public MyClass( String name ) {
       this.name = name;
       this.address = address;
    }
}
Of course, the code still continued to compile and run, but with one extra line: the this.address = address assignment. Now the two address fields just resolve to the same variable... This is wasteful and pointless coding, and almost impossible to detect automatically.

--- Not true. IntellijIDEA picks this up with the comment "Silly Assignment". KeithDavidson. ---

--I Second that. Eclipse also recognizes the above case as an unnecessary assignment. --Erik Alm

What if I leave out this?#

You can always leave out the this though, if you use different names for each local instance. Problem is, sometimes it can be really confusing when you don't know which variables are instance variables, and which are locals. Example:
...
    public void myMethod( String userName, String address, String somethingElse )
    {
        String myAddress = address.substring(1);
        anAddress = myAddress;
        somethingElse = somethingElse.toUpperCase();
        if( somethingElse.startsWith("+") )
        {
            userName = userName.trim();
            name = userName;
        }
    }
...

As you can see, figuring out which variables are instance variables requires looking through the entire method. When you meet new code for the first time, this often means constant scrolling back and forth. You can always document all of the side effects in the javadoc, like which instance variable gets changed and why, but isn't it easier to just write clear code?

Note that the situation becomes even more confusing if you use inner classes.

Better habits - naming the instance variables consistently#

I personally reserve the normal variable names (first word lowercase, next words Capitalized) for the local variables only, and prefix all instance variables with "m_". This is BTW recommended by the Avalon coding standard, a very good document. This way it's always clear which variable belongs where (and it's quite a bit shorter than using this.

...
    public void myMethod( String userName, String address, String somethingElse )
    {
        String myAddress = address.substring(1);
        m_anAddress = myAddress;
        somethingElse = somethingElse.toUpperCase();
        if( somethingElse.startsWith("+") )
        {
            userName = userName.trim();
            m_name = userName;
        }
    }
...

If you start naming your variables with the "m_" -prefix, then probably it's a good idea to name static variables (=class variables) with "c_". Using "s_" might confuse some people to think the variable is a String.

Good uses of this#

There are a few cases in which the explicit use of this is a good idea:

  • When you wish to refer to the parent instance of an inner class, you need this.
  • When you refer to the actual object itself (since there is no other way).

Beg to differ.

I see your point, but the stylistic form of a constructor, which receives parameters with the same name as class members and uses "this.x = x;" is very common, and hence easy to understand.

The example you raise is quite rare, and would usualy be avoided. As you say, even if not it only makes the code very slightly less efficient.

On the other hand, marking variables the way you do makes bloats the code with names.

And using this.variablename instead of m_variablename does not? :-) --JanneJalkanen
m_variablename makes most Java developers scoff because of the underscore, but it actually also breaks the Naming conventions for Java -- if you wanna follow them... --ErikAlm

The basic reason for naming both the variable and the member the same is that it indicates they are tightly bound.

- YishayMor


Your view is quite understandable, the suggestion with using "m_" is very good, BUT if you are coding EJB Entity Beans you usually DO NOT want variable names like "m_name" because that leads to methods lik "getM_name" which is pretty anal. This critic might seem to be pointless when not working in an EJB-environment (like JSPWiki), BUT why use different code styles? May be some time in the future there IS need for changing to EJB and then you're stuck with nasty names.

I like best a different style: naming method parameters with a prefix "a_" and local variables with prefix "l_", so it gets:

public String setName ( String a_name){ String l_name = a_name.trim(); name = l_name; }

Then you can let the "this." away also and have no problems with EJBs.

- Till Baumgaertel

Yes, that is another way of doing it, and also a smart solution to the same problem.

But really, do EJB's always assume that the getter and setter method names must match with the field name? At least in the standard JavaBeans spec this is not so; it is just a recommendation. Besides, if the field is a private member anyway, nobody else is supposed to know anything about it...

-- JanneJalkanen


Good ideas, everyone. One thing, though: you mentioned that the extra (and pointless) variable assignment is "almost impossible to detect automatically." Various IDEs (Eclipse as an example) catch this with a "The assignment to variable X has no effect" warning. Just thought I'd share. Thanks!

- Andrew Stott


Also various IDEs (i.e. IntelliJ) recognize the scope of a variable, and give it different colours accordingly. Thus it is no longer necessary to give variables special names to show their scope (m_someVar or c_someVar). IMHO it is right that the IDE helps you to see such things, and it is bad to use artificial names for your variables.

Indeed, assignments such as this.someVar = someVar result in a warning and thus it is no problem to use this. For me it is very important to give natural names to variables, without having to resort to artificial conventions. It reminds me of the horrors of MSFT's Hungarian notation: they used to prefix variables to show their type. This could be done only in pre-OO times where people coded alsmost exclusively with native types. Now that they could no longer use the Hungarian notation they found another artificial use for variable prefixes, this time it is the scope of the variable. What's next :). Suddder.

Thus it often happens that the member has the same name as the parameter, and you have to use this.someVar.

The problem with artificial conventions is that everyone does it differently. Therefore when mixing code from different sources, you get an unholy mixture of conventions. I think everyone should stick to the coding style and recommendations as defined by the "owner/inventor" of the environment. For Java that is SUN, for .NET that is MSFT.

When I program Java, I therefore use

for (...) {
  ...
}
and when I program C# I use
for (...)
{
  ...
}

simply because it is the "native" style for each environment. Sharing and reusing code would be easier if everyone stuck to this principle.

-- PeterMutsaers

Eclipse generates warnings when assigning a variable to itself. --PhilipVanBogaert

I guess a bit of explanation on the origins of this article are in place.

The times I've had to fix code over an SSH connection - with emacs or vi as my only tool - cannot be counted. In such cases, you can no longer rely on a certain IDE to catch your mistakes, you have to do them yourself. Also, not all IDEs are equal; often I had to change between one IDE environment and then another very quickly. This particular article was actually written while I was working for a Java consultancy company, and had to learn to adapt quickly to differing coding environments... and had just to debug a particularly nasty bug that turned out to be a simple scope error.

Relying on the IDE to make corrections and trapping your mistakes is kinda like not learning to walk because you have cars. I've seen horrible or crappy code by people who did not understand what they were doing, simply because they rely on the IDEs, and this is because they never bothered to learn the basics of their trade - they just trusted their IDE environments. We all hate web designers who only use FrontPage and call themselves HTML specialists, yes?

It's kinda like sometimes you see Java code that works only on Windows, simply because the author has always assumed that the file system is not case sensitive. That drives you mad when trying to fix those bugs... Or vice versa, having someone assume that files "FooBar.txt" and "foobar.txt" are somehow magically different file on all systems. This is simple sloppiness and lazyness - the "it works for me"-syndrome.

-- JanneJalkanen

I agree with PeterMutsaers, having worked with jspwiki recently, making various modifications to use it for our intranet, I always wondered what the hell the "m_" prefix meant until I stumbled upon this page. Completely unnecessary and confusing.

-- KeithDavidson


On the contrary I believe using the this keyword is very GOOD.
There is a BIG difference between writing this.name = "Luca"; and writing m_name = "Luca";. In the first case it is perfectly clear to anyone reading the code that name is an instance variable. In the second case, you have to know the author's naming convention to reach the same conclusion. The first notation is straightforward programing style, whereas the second notation relies on a naming convention.
Face it, all Java programers worlwide agreeing on the same naming convention is NEVER going to happen.

The same applies to classes.
Anybody reading Singleton.instance = new Singleton(); instantly knows that instance is a static variable of class Singleton. Again, you need to know the author's naming convention to understand that c_instance = new Singleton(); is a static variable.

Method invokation benefits from the same notation. It is a good thing to write this.getName() and Singleton.getInstance() because it helps understanding the interactions between the objects and classes.
People learning Java (or any other O.O. language) often confuse the class itself with an instance of the class. Using this notation usually helps.

About the example at the top of this page...
IMHO it does not show that using this is a bad habit.
It shows that you can benefit from adopting a naming convention that distinguishes method arguments from local/instance/static variables. --LucaNadalini


It's a pretty big (il)logical leap to go from "IDEs make naming conventions unnecessary" to "IDEs lead to bad programming." Naming conventions like that are a hack. They might be more necessary in C because the language will accept sloppy typing, but in Java, it's either a no-op or an error that the compiler will catch. That applies regardless of whether you are using an IDE; it just so happens that the IDE will catch the error sooner. --AnonymousCoward


I'd also like to point out that without consistent naming, it's difficult to know whether an assignment is to an instance variable, or a local variable.

It confuses the heck out of me every time I look at any source code which follows the "official" rules, mostly because the coders never bother to use "this." consistently. If there was a rule that all instance references MUST begin with a "this.", then I would have no problem. But unfortunately, this is not the case (and not following that rule would be a lot more complicated to check for...)

This article was originally written in 2001, when practically NO IDEs could catch this sort of stuff. While most of them do now, I still find it problematic to think that the user must rely on IDE functionality to catch errors resulting from stuff like this.

The JSPWikiCodingStandard explains the standards used in JSPWiki development.

--JanneJalkanen, 24-Nov-2007

I don't see any bad point on depending on tools to catch human errors. Human are unreliable, even experts cannot easily write a program without bug. So relying on IDE for "this." usage problem should not be sin, right? And talking about readability, I opt for "this" rather than "m_" that, like PeterMutsaers said, it looks artificial.

--Ruxo, 4-Jun-2008

I'm a fan of using language constructs rather than arbitrary conventions wherever possible. Thus, I prefer "this." to "m_". :-) And yes, java (and eclipse) can give warnings on the "assignment-does-nothing" accident. I use this. everywhere.

--David Van Brink, 17-Apr-2010

Add new attachment

Only authorized users are allowed to upload new attachments.
« This page (revision-27) was last changed on 18-Apr-2011 01:43 by 63.249.119.13