15 February 2012

Improper inheritance and light-hearted downcast

And here is maybe the worst design I've ever seen - directly from production-released code, of course...


Inheritance is a key feature in object-oriented programming languages, providing support for both specialization and flexible extensibility. But... using inheritance just to use it can drive to horrible design cases, where distinction between superclass/interfaces and different subclasses is improper and extensibility is actually impossible. This is the case of a real-life production code I was lucky enough to see:

public interface InterfaceX {
   public abstract void aMethodX();
}

public interface InterfaceY {
   public abstract String aMethodY(final String s);
}
 
Class FatImplementation implements both InterfaceX and InterfaceY:
 
public class FatImplementation implements InterfaceX, InterfaceY {
   public void aMethodX() {
      ...
   } 
 
   public String aMethodY(final String s) {
      ...
      return ...;
   }
}
 
And... Ladies and Gentlemen... the crazy client class, whose method is casting to InterfaceX an InterfaceY reference, relying on the fact that FatImplementation implements both interfaces:

public class CrazyClass {
 public void theCrazyCastingMethod(final InterfaceY y) {
  ...
  ((InterfaceX)y).aMethodX();
 }
}

This is an improper use of abstraction - inheritance programming model, since the cast succeeds only with a specific implementation (FatImplementation) of given interface and polymorphism is actually not possible.
... ... ... poorly and foolishly designed, isn't it? And... what if I said that InterfaceX and InterfaceY, in the original code, where StatefulXXX and StatelessXXX? So... FatImplementation was stateful and stateless at the same time! AAAAAAHHHH!

1 comment:

  1. about a class which is both Stateful and Stateless, in eclipse GET you can find this beauty:

    ResizableEditPolicy extends NonResizableEditPolicy

    ReplyDelete