Override And Call Inherited Idiom

An idiom for specializing a method in an abstract class. [CategoryIdiom] [AntiIdiom] [CeePlusPlusIdioms] [JavaIdiom]

In an abstract class, it is common to provide a virtual method with basic functionality which is to be extended by a subclass method. The subclass provides an overriding method and will [is supposed to] call the inherited method. This is mainly defined since it is commonly used and their are often better (safer/clearer) alternatives. In that sense, this might be an AntiIdiom. This idiom is common in many languages, but in C++ and Java in particular.

For instance (some liberties taken with C++ish syntax for compact presentation):

 abstract class Drawable_Item

/** Override in a subclass and call the inherited method. */ virtual void draw(Context context) { draw_border(context); update(); } }

Then a subclass would override draw:

 class My_Drawable_Item
	virtual void draw(Context context)

This idiom *does* work, however, it depends on the subclasser to do four things:

  1. ) Remember to override the method in the first place (it is not abstract/pure virtual).
  2. ) Remember to call the inherited method
  3. ) Call the correct inherited method (a problem when the base class is refactored)
  4. ) Remember to call it in the right order (often undocumented).

The third one is more of an issue in C++ than in Java, since in C++, the class must be explicitly specified (Drawable_Item::draw(..)). If the direct base class changes due to refactoring, these calls must be updated as well. Multiple inheritance can also cause confusion, particularly with call ordering. In Java, the *super* keyword provides some safety.

The last one is often not clearly documented in an API and can cause subtle problems. In this case, the inherited method calls update(..), which we might presume should be called *after* the subclass drawing completes. There is often no way of knowing this without detailed internal knowledge.

On the plus side, this idiom allows common code to bubble up to superclasses rather than being cut and paste in subclass code. Since it causes its own problems, however, it might be better to take a look at NonVirtualCallsPureVirtualIdiom/TemplateMethodPattern.


View edit of April 4, 2008 or FindPage with title or text search