Subscribe to our mailing list

* indicates required
Close

Tuesday, February 03, 2009

Why super( ) sucks

One complaint I heard someone make recently, in the context of JavaScript not having a true inheritance model, is that there is no super() in JavaScript. Somebody, in a forum somewhere, actually whined and moaned about not being able to call super(). I believe the whiner was a Java programmer.

There shouldn't be a super() in Java, either, though. That's the real issue.

I'm flabbergasted that anyone thinks super() is a meaningful thing to have to write, in any language. What could be more obscure and arcane than super()? It's totally cryptic. It's shorthand for "go invoke a method of my parent that I happen to have intimate knowledge of. Never mind the side effects, I'm clairvoyant enough to understand all that, even if my parent's concrete implementation changed without my knowing it."

I thought secret knowledge and hidden dependencies were supposed to be evil.

2 comments:

  1. I can't say I follow: how is the way the behavior super() may change any different from the way the behavior of externalMethod() may change?

    ReplyDelete
  2. There are two super's in Java.

    One is the constructor form that actually takes arguments. It's always called by a subclass (that is, if it's not listed, the no-arg super() is called). How else are you proposing to send arguments to superclasses requiring arguments to be constructed?

    The second use of super is used to call a superclass's implementation of a method (or a hidden variable in pathological cases). These super calls are necessary if I want to subclass another class and filter it's output. That is, I might write an extended XML handler that calls super to do some work and then logs what happens or drops out some debug.

    Sometimes, you can get around the need to call super methods by encapsulating an instance rather than extending the class. In general, that's good OO practice. But if you need an instance of a class, not of an interface, as you do with abstract base class patterns (e.g. InputStream in Java) you have no choice but to extend.

    Even if I encapsulate, I still have to call the method. So it's really a matter of writing classes for extension and not allowing methods to be extended that shouldn't be (e.g. ones that are called from constructors to do critical work).

    ReplyDelete

Add a comment. Registration required because trolls.