A Funny Java Flavoured Look at the World

Wednesday, April 26, 2006

Why you should use the this keyword

I have recently turned on CheckStyle as I blogged about earlier and I was saying I thought it had improved my coding style and the quality of the code I was writing.

I have turned on the rule called Require This under the group coding problems

Checks that code doesn't rely on the "this." default, i.e. references to instance variables and methods of the present object are explicitly of the form "this.varName" or "this.methodName(args)".

To start with I found it really annoying because it would keep moaning on at me to keep putting this infront of class variables and the Name of the class for Static variables.

I persisted with it because I thought someone must have made this rule for a reason. Today I have started to feel it paying off because now when I look at the code I can see what type of variables they are instantly. It seems more straight forward when you know what a static variables and what a class variables and finally what are the method variables, they are easy to spot because they are ones that aren't so long.

I have also found that while I am putting this infront of a variable or the class name for static variables I am now considering what level the variable should be at. If I think that the variable is going to be used by more than one method then I bring it up to be a class variable. I know this is basic programming but I was interested by the fact that I am now thinking about this more. I am also bringing up more variables to be static final variables.

I was thinking about doing something like this before in eclipse but by using the editor and colouring the different variables in different colours. I did some of the variables but the different colours looked a bit confusing but with using the this keyword everything is becoming a lot clearer.

It should also have some benefits when someone else comes to look at the code I have been writing because they should be able to get a clear idea about the variables being used and what level they are.

if you like this post you should read my blog entry using final variables which also has a link to a sample chapter



8 Comments:

  • Well, some IDEs like IDEA will paint your static vars, instance vars and local vars in different colors, so it's easy to see which type of variable you have.

    By Anonymous Anonymous, at Thu Apr 27, 09:25:00 am 2006  

  • We use another coding standard - instance variables are prefixed with i (iSurname, iForename, ...), while static non-constant variables are prefixed by c (cCache, ...). Works well too.

    By Anonymous Anonymous, at Thu Apr 27, 01:12:00 pm 2006  

  • I have seen some code with standards similar to method mentioned above but different people used different standards.

    Eclipse also has the functionality to colour different variables but in the end it looked a bit confusing with four different colours in a method. I recommend you give using the this keyword a try. It seems a bit wierd at first but I soon found that it became quite useful.

    thanks for the comments

    By Blogger The Hosk, at Thu Apr 27, 07:38:00 pm 2006  

  • From a custom application development I would just avoid static altogether except for the following two situations:

    public static final int CONSTANTS

    public final class UtilityClass {
    public static void utilityMethod()
    private UtilityClass();
    }

    Unless I am building a framework. And even with frameworks I don't normally use static variables. Mind you I also avoid singletons like a plague and use Dependency Injection when I can.

    Mutable statics are pretty bad when it comes to clusterability. Primarily since it won't work because the values are not shared across JVMs.

    By Blogger Archimedes Trajano, at Fri Apr 28, 03:52:00 am 2006  

  • I agree with the comments about using static constants. I don't use them in my code very often.

    I was using some static constants in some Junit tests.

    I used them in the code for writing a String constant for the user setting the type of connection.

    public static final String ACCESS = "ACCESS"

    When I write Junit tests if an expected value is the same for a number of tests I might make it a static final so I don't have to type it in many times and only use one string vaule. I don't know if this is the correct way, my Junit test code is pretty shabby I'm afraid.

    By Blogger The Hosk, at Fri Apr 28, 11:26:00 am 2006  

  • "Some people will obsessively put this in front of every method call and field reference, arguing that it makes it “clearer and more explicit.” Don’t do it. There’s a reason that we use high-level languages: they do things for us. If you put this in when it’s not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they’ve read won’t use this everywhere. Following a consistent and straightforward coding style saves time and money."

    (From Bruce Eckel's Thinking in Java, 3rd/4th editions)

    I have to agree most wholeheartedly with Bruce, here: please do not use this coding style.

    The best writing (generally) is that which is concise and this applies to source code as much as it does to English. The general rule should therefore be: "Write the code that is necessary AND NO MORE."

    By adding this to all your references you make those situations where the this keyword is actually necessary more-easily identified.

    It is useful to be able to differentiate between local vairables and data members/fields (although this is less of a problem in a modern IDE with syntax colouring, pop-up hints, etc.). A more usual approach would be to add a prefix such as "m_" or even just "_" to all your member variables. This has the added advantage that you can't "forget" to add it each time you use the reference.

    In Java, as there are no globals, it should already be obvious what you are referencing. (Compare with C++ where you could be accessing a member variable OR global data, a helper member function or a library routine. I'd still not add this-> to everything in C++, though!)

    I'm also very concerned about your approach to promoting local variables to class-members generally because you're using them in more than one place. Are you doing any OO design at all before coding? This should identify the member data you need before you start. Anything that isn't member data shouldn't be declared at class level and should be local to the method, regardless of how "convenient" it is to have it already - good practice suggests you should declare everything with the smallest scope possible.

    Finally, as regards your JUnit code, if the value you are testing each time is the same thing (rather than two different things with the same value) then having a constant to represent it isn't a bad idea (especially if there's a chance it'll change in the future). Consider, also, using an "Object Mother" approach in which you have a class that exists to generate the objects that you're using in your tests, rather than bloating the test class itself with superfluous data values and objects (google for "Object Mother" and you'll find more details).

    Rob.

    By Anonymous Anonymous, at Wed May 31, 11:57:00 am 2006  

  • I forgot to add:

    I persisted with it because I thought someone must have made this rule for a reason.

    Doing what other people do without knowing why they do it is a bad idea, because you won't know what the drawbacks are and/or when you shouldn't use the approach.

    I've personally been searching all year (since I first came across it in January) for a valid reason why people do the "this" keyword thing (this is how I found your post), so far without success.

    One common (invalid) reason I've found is "because then the IDE auto-complete kicks in". Sorry, but laziness isn't exactly the best excuse for bad coding style, in my book!

    Mostly, however, the advantages claimed are either matched or exceed by simply having a coding standard to mark your member variables with a common prefix, such as an underscore.

    Rob.

    By Anonymous Anonymous, at Wed May 31, 12:05:00 pm 2006  

  • Oops! This:

    By adding this to all your references you make those situations where the this keyword is actually necessary more-easily identified.

    should have read:

    By avoiding adding this ...

    [I'll stop monopolising the site now, I promise]

    Rob.

    By Anonymous Anonymous, at Wed May 31, 12:19:00 pm 2006  

Post a Comment

<< Home