Yuriy Zubarev

Obscure Inheritance or Homomorphism

2011-11-22

Here is a rather simple class diagram:

At the first glance it makes sense and it’s rather self explanatory. If you’re an experienced developer you can actually scream “bloody murder” right away, but let’s take it slow. Here is a hint that something evil is happening here. The rest of a system has an explicit dependency on Displayable interface, which is a good intent, but the details are very ominous. Every implementation block always has the same structure:

if ("list".equals(displayble.getName())) then {
    ...
} else if ("paragraph".equals(displayble.getName())) then {
    ...
} else if ("section".equals(displayble.getName())) then {
    ...
}

This is a complete fiasco in abstraction, plain and simple. The code above might as well look like:

if (displayable instanceof DisplayableList) {
    ...
} else if (displayable instanceof DisplayableParagraph) then {
    ...
} else if (displayable instanceof DisplayableSectionName) then {
    ...
}

The only thing that the base interface exposes is getName() method which is akin to Object.getClass() method. It doesn’t encapsulate any useful behavior, it just provides a hook to query object’s implementation structure.

Depending on the original intent, this could be an example of either Obscure Inheritance or Homomorphism or both.

Inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support.

In this situation there is zero code reuse. Sub-typing is rather superficial: it offers no more than a fact that the classes have getName() method. The method itself is not what consumers care about, but a hook to make further decisions based on essentially internal structure of a class. This is the example of Obscure Inheritance.

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.

The word derives from the Greek “πολυμορφισμός” meaning “having multiple forms”.

This case presents the exact opposite: different data types are handled without a uniformed interface. The presence of “if” statement per data type is the culprit. This is an example of Homomorphism.

Alternative

This family of classes deal with tree-like structures to display lists, headings, paragraphs, etc. There is a software design pattern that deals with this exact concern: composite pattern. The key benefit, as applied to this case, is “… lets clients treat individual objects and compositions uniformly”.

 

Comments :

blog comments powered by Disqus