exceptionz

Thoughts on Technology, Methodology and Programming.

Code Smell: CallSuper

Posted by Marcus Wyatt on 12 August 2005

CallSuper is a minor smell (or anti-pattern if you like) that crops up from time to time in OO frameworks. Its symptoms are pretty easy to spot. You are inheriting from a super-class in order to plug into some framework. The documentation says something like “to do your own thing, just subclass the process method. However it’s important to remember to start your method with a call to the super-class”.

An example might be something like this.

public class EventHandler {
   public void handle (BankingEvent e){ 
      housekeeping(e); 
   } 
}
public class TransferEventHandler extends EventHandler {
   public void handle(BankingEvent e) { 
      super.handle(e); 
      initiateTransfer(e); 
   }
}

Whenever you have to remember to do something every time, that’s a sign of a bad API. Instead the API should remember the housekeeping call for you. The usual way to do this is to make the handle method a Template Method, like this. 

public class EventHandler {
   public void handle (BankingEvent e) {
      housekeeping(e);
      doHandle(e);
   }
}
 
protected void doHandle(BankingEvent e) {
 
}
 
public class TransferEventHandler extends EventHandler {
   protected void doHandle(BankingEvent e) {
      initiateTransfer(e);
   }   
}

Here the super-class defines the public method and provides a separate method (often referred to as a hook method) for the subclass to override. The subclass writer now doesn’t have to worry his ugly head about calls to super. Furthermore the super-class writer is free to add calls after the subclass method if she wishes.

You can read Martin Fowler’s whole post here.

tags: , ,

Currently listening to: a, Part II – Winamp *** 2. Ayla – Ayla, Part II

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: