« My software design principles | Main | Exceptions in Java are your friend »
Saturday
Sep052009

Don't prefix Java method calls with this or super

Here's one thing I stumbled over in Java code several times. Some developers believe that prefixing method calls with "this" or "super" produces more readable code, as in

this.method();
super.method();

Supposedly this would make it clearer where to find the actual method definition. I don't think so. When prefixing with "this", the method can be defined anywhere in the class hierarchy. Also, since Java doesn't support functions outside a class context, "this" would be redundant.

Prefixing with "super" is plain wrong as it forces the execution of a method in one of the super classes, even if the method is overridden in the actual class. As the code evolves, this may lead to tricky bugs. Also, it basically breaks polymorphism, which means that Java decides at runtime which method implementation is called. In the case of an implementation in the super class this is not obvious as Java doesn't allow to change the class hierarchy at runtime, but functionally it's very much the same thing as casting an interface down to its implementation class.

Bottom line. Never prefix method calls with "super", except when explicitly calling the implementation in the super class from an overridden method. And I don't see a reason to prefix it with "this".

Reader Comments

There are no comments for this journal entry. To create a new comment, use the form below.

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>