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) { draw_upside_down_panda(context); Drawable_Item::draw(context); } }This idiom *does* work, however, it depends on the subclasser to do four things:
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.