This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Using Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using "this" Operator and it Watch "Using "this" Operator and it New topic
Author

Using "this" Operator and it's relation to readability

Wasim Ayoubi
Ranch Hand

Joined: Nov 21, 2004
Posts: 46
Hi All,
I am doing some code refactoring and wondering if using "this" operator is an addon to readability or not.

public class XX{
String foo;

public String getFoo(){
return foo;
}

public void doX(){
......
......
this.getFoo();
//or
getFoo();
}
}

I believe using the this.getFoo() is better, at least you can figure it is not a static method on the class and you are getting a state of an object.


Wasim Ayoubi<br />SCJA1.0(BETA), SCJP1.4, SCWCD1.4<br />Next ???
Wasim Ayoubi
Ranch Hand

Joined: Nov 21, 2004
Posts: 46
and even in the getter method

public String getFoo(){
return this.foo;
}
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
I'm not convinced it makes the code any clearer in most circumstances. Bear in mind that including or not including 'this' makes no difference to the resulting class file (the compiler will insert 'this' for you anyway). So this question reduces to one of aesthestics in source code only.

To me at least, it's usually pretty clear from the structure of the class what type of method is being invoked. If I see getFoo() and need to know more, I immediately scroll back up the source code/API documentation, find the method and see if it's static or not. I only ever use 'this' when there is the possibility for confusion over variable names, or when there is really complex code in which using 'this' actually makes things clearer (which is rare). On the whole, inserting 'this' everywhere just gets tedious and annoying, and I think (in my opinion) makes code more cluttered and therefore harder to read.

You should also bear in mind that:

this.getFoo()

is valid regardless of whether getFoo() is static or not. Most methods we see and invoke are non-static, so in fact, if you really want/need to be absolutely clear, you should be invoking a static method by referencing the class name:

XX.getFoo()

and then just use getFoo(), without the 'this', for refering to non-static methods. This is more conventional and, assuming you have fewer static than instance methods, will make the code slightly clearer and less cluttered.


Oh, and by the way, 'this' is a keyword, not an operator - an operator is something which modifies the value of a variable, such as the arithmetic and logic operators, or the assignments or comparison tests (including the 'instanceof' test, which is classed as an operator - see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/other.html ).
[ March 16, 2006: Message edited by: Charles Lyons ]

Charles Lyons (SCJP 1.4, April 2003; SCJP 5, Dec 2006; SCWCD 1.4b, April 2004)
Author of OCEJWCD Study Companion for Oracle Exam 1Z0-899 (ISBN 0955160340 / Amazon Amazon UK )
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
I agree with Charles.

Also note that making a difference in how you invoke a static or an instance method makes the code less flexible: changing a method from static to non-static (or the other way around) becomes more work.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Originally posted by Ilja Preuss:
I agree with Charles.

Also note that making a difference in how you invoke a static or an instance method makes the code less flexible: changing a method from static to non-static (or the other way around) becomes more work.


I second, in agreement. I worked with someone's code before where they put this, to access every instance method and variable. Don't think the code is more readable -- just longer.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Henry Wong:
Don't think the code is more readable -- just longer.


Yes. To me it typically feels more like clutter than like helpful information. But that's probably a matter of what you are used to...
ak pillai
author
Ranch Hand

Joined: Feb 11, 2006
Posts: 288
If you are a beginner it makes sense to use this. But once you are used to it, then it is more of a clutter. Beginners can easiliy fall into the following pitfall:






The above code prints "original". The constructor should be written with "this" as shown below to get the output of assigned.




java j2ee job interview questions with answers | Learn the core concepts and the key areas
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by ak pillai:
Beginners can easiliy fall into the following pitfall:


Doesn't the compiler warn about an assignment without effect in that case? The Eclipse compiler does...
Charles Lyons
Author
Ranch Hand

Joined: Mar 27, 2003
Posts: 836
Originally posted by ak pillai:
If you are a beginner it makes sense to use this. But once you are used to it, then it is more of a clutter. Beginners can easiliy fall into the following pitfall
In practise, the purpose of 'this' is to reduce confusion over instance/method-local variable names and between inner/outer classes; as I said earlier:
Originally posted by Charles Lyons:
I only ever use 'this' when there is the possibility for confusion over variable names
So whether you're an expert or a beginner, you would always use:
in your example, unless you wanted to rename the variables (which is actually less clear - I think using 'this' in the previous example is beneficial).
[ March 17, 2006: Message edited by: Charles Lyons ]
Reid M. Pinchback
Ranch Hand

Joined: Jan 25, 2002
Posts: 775
Originally posted by Wasim Ayoubi:
I am doing some code refactoring and wondering if using "this" operator is an addon to readability or not.


As you can probably tell by now, everybody has various reasons for doing or not doing something that you'll have to weigh for your situation. Mine tends to be "if I have to type more code to make something clear, maybe my code isn't clear enough for other reasons that matter more, and I should fix those things first".

For example, if you have a method that is 10 lines of code that you can see at a glance, "this", except when the compiler needs it, probably isn't going to add value. Not so much confusion in code (particularly code you wrote yourself) when you can see it in its entirety at a single glance.

On the other hand, if you have methods that are 1000 lines of code, then you probably scrounge for or dream up every naming and commenting convention you probably can to keep track of what is going on because it is really taxing to keep stuck in your brain everything you have to remember about what was happening 100 lines up (scrolled out of view) or what is happening next 100 lines below (not net scrolled into view).

The problem in the latter case isn't that you need a bunch of conventions to survive the situation, the problem is that you shouldn't be in that situation in the first place. Longer methods motivate conventions, but longer methods aren't as strong as more compact methods whose purpose and name are obvious. When you have that, syntactic sugar and variable naming patterns don't seem like such a big issue. Not saying conventions are bad, just that you get to minimize the concerns about them as you strengthen other aspects of the code.

By the time I'm inclined worry about things like "this", I'm more inclined look for whether or not the class is too big in the first place.


Reid - SCJP2 (April 2002)
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I recommend using an automatic code style enforcement (e.g. CheckStyle) to prevent the use of all types of redundantly redundant redundancy. This includes extraneous uses of the 'this' qualifier.

Redundant redundancy has never helped anybody - it has only ever obscured the otherwise clearer clarity for those who are not as well versed as they should be.

Ever seen one of these?



There is something very similar to this well stashed away in a particular JDK 1.5 implementation


Tony Morris
Java Q&A (FAQ, Trivia)
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Tony Morris:
Redundant redundancy has never helped anybody


That's kind of tautological, isn't it?

On the other hand, there is redundancy that helps. For example

Customer customer = customers.get(customerIndex);

has some kind of redundance, but it helps to communicate, both to people and to the compiler (whether that benefit is worth the costs of redundancy is a matter of personal opinion, probably).

So I don't think the answer is as straight forward...
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Tautological tautology is great
I don't understand your example and how it demonstrates redundantly redundant redundancy.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
As often happens, by using words like always and never, you encourage others to question the limits of your statements. There are things that may look redundant to some people, which may nonetheless be useful. In Ilja's example, "customer" is used four times in the same line; this may well seem redundant to some people. Especially those who are more used to scripting languages. And indeed, if any of the variables involved are local, I would be inclined to shorten the variable names (especially customerIndex). Unless the method/block must be unusually long for some reason - normally I'd try to keep methods short enough that for any given variable, it's pretty obvious what it refers to, because the declaration is just a few lines away. That doesn't always work out though. Anyway, long variable names are one programming technique that seem redundant to some, yet are often useful in any context where the significance of the variable is not immediately clear otherwise.

Taking another tack, redundancy can be a very good thing for something like, say, a component on the space shuttle. Some widget may fail, and having a backup widget (or two or three) is usally a good idea. This sort of redundancy for the sake of redundancy is usually much less useful in software engineering, I think, but it does come up now and then. For example when moving a file using Java. One might typically first try File.renameTo(). But if it fails, a possible reason for that is because the target directory is on a different filesystem. (Depending on OS and other issues.) In which case it may make sense to use a slower copy-and-delete strategy instead. This, again, can be viewed as a sort of redundant backup system, nonetheless beneficial. However it's not purely redundant, since the backup code has some different capabilities than the primary code (using renameTo()) did.

I think this sort of "redundancy" is probably not what you had in mind. But it is included in what many people may think of when "redundancy" is mentioned. You say "Redundant redundancy has never helped anybody" - in the tautological sense that's certainly true, but in wider senses, it's not necessarily true. Ilja's post and mine explore the limits of when redundancy may be useful, or not.

Anyway, I would agree that most forms of redundancy - let's say "pure" redundancy - are useless (by definition) and counterproductive (by mild obfuscation) in programming. E.g. using "this" where it's not necessary, or declaring a member of an interface to be public. I suspect there's no real disagreement here; we're just bringing in slightly different definitions of what "redundant" might mean.


"I'm not back." - Bill Harding, Twister
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
What Jim said.

Another form of very helpful redundancy is expressing what the code does not only in the production code, but additionally in unit and system tests.

I think there is a pattern here: redundancy is good where you need to make sure that you got something right - you express the same thing in different ways and than see whether they lead to the same result. If they don't, at least one of them must be wrong.

Another prominent (non-software) example of helpful redundancy is double-entry bookkeeping.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I'd like to question and subsequently argue in favour of terms like 'always' and 'never'. I'd also like to point out the major implications (for example, rewriting mathematical history) should these terms be proven to be illegitimate in the context that they have been used here. That is to say, if what you say is right, there are profound consequences - but I will not rule out your claim.

Prior reading includes:
- Goedels Thereom of Undecidability (aka Incompleteness)
- A thorough understanding of reductio ad absurdum (aka method of contradiction - a form of mathematical induction)
- Of less importance, method of infinite descent (another form of induction)

I will of course, return the favour and read up on whatever is requested. I think this is a crucially important step so that we find a common premise on which to argue (this is often the single biggest hurdle to overcome). For example, you might like to exclude the legimitacy of the method of contradiction, in which case, we have no common ground, and so must digress further.

I assume that there is a genuine interest in learning and understanding 'reality' (for some definition of) - in contrast to a religious subscription to something that I simply don't subscribe to - which case, we simply walk.
So how about it? Once and for all? Shall we take it to the relevant forum?
Reid M. Pinchback
Ranch Hand

Joined: Jan 25, 2002
Posts: 775
Right about now I've got that Alice-in-the-looking-glass feeling...
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Tony, I believe a thorough understanding of reductio ad absurdum would include a study of intuitionism, which rejects the law of the excluded middle, upon which reductio critically depends. And it rejects the concept of infinity, so naturally infinite descent is out as well. It only permits the discussion of objects that can be constructively described by human beings; and since all computer programs are such objects, I think it is completely relevant to your post.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Paul Clapham:
Tony, I believe a thorough understanding of reductio ad absurdum would include a study of intuitionism, which rejects the law of the excluded middle, upon which reductio critically depends. And it rejects the concept of infinity, so naturally infinite descent is out as well. It only permits the discussion of objects that can be constructively described by human beings; and since all computer programs are such objects, I think it is completely relevant to your post.


If I understand you correctly, I do not propose a "Theory of Everything" using the aforementioned methods, which as you point out, cannot exist in symbiosis. In other words, I agree with your reasoning, except the conclusion that not having an understanding would not be beneficial. Using two or more contrasting methods to derive the same conclusion is exactly the intent.

I have done it before - in fact, I have been discussing it with a select few for years - and I've had many holes pointed out along the way (and pointed out holes myself). The reason I now propose such a debate is that the frequency of occurrences of these "holes" is diminishing to the point now of conceding by drawing a conclusion. A fresh perspective is required, otherwise, I am forced to conclude - and I hate concluding for fear of the brokenness that might lie around the corner The worst feeling ever! By not concluding, I can simply shift my reality
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I might point out that there are lots of people who are warning me against engaging such in a debate, since they believe that it will be utterly pointless for their own reasons. However, I am an optimist - perhaps foolishly.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Tony, I don't think we need to get that philosophical here. Do you accept proof by counter-example? There are at least two counter-examples above which seem to prove that redundancy in fact helps people now and again.
[ March 20, 2006: Message edited by: Ilja Preuss ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Tony, I'm not even sure what it is you think I've said that you plan to argue against. I'm not saying words like "always" and "never" can never be used. In fact there are many relatively well-defined contexts such as mathematics in which they can serve us quite well. However you frequently emply such words in much more loosely defined contexts of human language, such as this thread. Where I think the biggest issue is that we don't all mean the same thing when we refer to redundancy. An issue I tried to address in my post. However after reading your response, it seems we're no closer to a useful understanding. Too bad.

Unfortunately, based on the rather limited success of past discussions we've had, I suspect a prolonged discussion such as you propose would probably result in too much and little in the way of enlightenment for either of us. I think it's unlikely to be worth the effort. Thanks, but I'm not interested.
[ March 20, 2006: Message edited by: Jim Yingst ]
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Is anyone else interested in applying ideas from Bose-Einstein Condensation to certain "when hell freezes over" conditions in software engineering?


There is no emoticon for what I am feeling!
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

Originally posted by Wasim Ayoubi:
Hi All,
I am doing some code refactoring and wondering if using "this" operator is an addon to readability or not.

public class XX{
String foo;

public String getFoo(){
return foo;
}

public void doX(){
......
......
this.getFoo();
//or
getFoo();
}
}

I believe using the this.getFoo() is better, at least you can figure it is not a static method on the class and you are getting a state of an object.



this alone adds nothing. The only real discriminator would be


As someone mentioned this helps differentiate in the case of inner classes. If you do not do this for all of the calls of an inner class that extends another class, you can't be immediately sure which method its calling, nor the effect of parent class changes on the methods called.

If the parent class adds a method, this can cause a call from the inner class to go to the parent class as opposed to the outer class. And you cant even see why by looking at the outer class. God forbid your parent class is in a library...

I consider this a Java flaw. I think there may be some annotations in 1.5 that help this but I don't know 1.5 yet.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

With respect to the original question, I offer this quote from Bruce Eckel...
Some people will obsessively put this in front of every ... 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...

(Footnote on page 169 of Thinking in Java, 4th edition.)


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
I agree with Bruce.

I have no idea what Tony and Jim are rambling about.

I like toast.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ken Blair:
I agree with Bruce.

I have no idea what Tony and Jim are rambling about.

I like toast.


Tony and Jim don't know what Tony and Jim are rambling about
I think there was just a miscommunication, as usual.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using "this" Operator and it's relation to readability