Improper inheritance and light-hearted downcast

This post war originally published here.

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:

1
2
3
4
5
6
7
public interface InterfaceX {
public abstract void aMethodX();
}

public interface InterfaceY {
public abstract String aMethodY(final String s);
}

Class FatImplementation implements both InterfaceX and InterfaceY:

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
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 - this is actually a wonderful violation of Liskov Substitution Principle.

… … … 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!