Don't prefix Java method calls with this or super
Saturday, September 5, 2009 at 5:39AM 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".
oliver |
Post a Comment |
Java 
Reader Comments