Call super

From CSSEMediaWiki
Revision as of 05:02, 18 July 2009 by JaninaVoigt (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The call super anti pattern occurs if a superclass requires base classes to call the superclass methods that they have overridden. This may be required if the superclass performs setup operations that are needed for it to work correctly and that are internal to the superclass and thus cannot be done from the subclass. It is also common if subclasses augment rather than replace the superclasses main task.

The specific issue with this anti pattern is the requirement to call the superclass method. This does not mean that it is bad practice in general to call superclass methods from overriding subclass methods. It is only bad for the superclass to expect that its method will be called.

Instead, the Template design pattern works better, where the superclass includes abstract methods that need to be overridden by the subclasses.

Example

JUnit test cases inherit from the TestCase class which contains the methods setUp() and tearDown(). They allow you to set up and remove your test environment, initialize variables you need etc. However, if you override the setUp() method, you need to remember to call the TestCase setUp() method as well or your test may not work correctly. This is a classic example of the Call Super anti pattern.

Liabilities

  • It is easy for the subclass to forget to call the superclass method, especially if the subclass is written by a different developer. This can easily introduce bugs and lead to the system not working correctly. Overall, it has a negative impact on the maintainability and understandability of the code.
  • It also requires developers to have an understanding of the superclass so that they know that the method needs to be called for the superclass to work correctly. Ideally, developers should only need to understand the public interface of the class.
  • If the subclass expects a certain type of behavior from the method it calls in the superclass, it will be affected if the behavior of the overridden method changes.
Personal tools