Composition is much better than inheritance

This article explains the pitfalls of inheritance, and offers a solution...

In this article I will have to use some ficticious class names etc due to the sensitivity of the project I am working on, so bear with me if some of the information seems a bit strange.

After working myself about 6 levels deep in inheritance I suddenly realised that my Factory class had a DateOfBirth.  This was certainly undesirable, but with my current model I couldn't do anything about it.  My options were to get rid of the inheritance for Factory and lose all of the benefits of doing that (having "AdditionalInformation" definable by the user for example), or to ignore the DateOfBirth and not show it in the GUI.

Both of these options were rubbish.  Instead of taking either of them, I went for a completely different option instead.  I decided to remove almost all inheritance within my model, and add composite relationships instead.

Now, instead of my Factory class descending indirectly from an ObjectWithAdditionalInformation it has no ancestor class at all.  In order to achieve the same functionality I now have a one-way relationship from Factory to the now renamed AdditionalInformationHolder class.  This class holds the additional information the user wants to enter, and the Factory creates an instance of it when it is first created.

I then created a Frame/UserControl which would hold the GUI for entering additional information, including its own ExpressionHandle.

The beauty of this approach is that I may now have any type of object within my model able to have additional information recorded against it if I so wish.  To implement the GUI I simply drop the Frame/UserControl onto the form of the object in question and set the root context of the ExpressionHandle.

Suddenly I have a model with hardly any inheritance in it at all.  I can make modifications to classes without having to check that it wont break any of the descendant classes (or their forms), and I haven't lost any functionality at all.

I strongly recommend that you use inheritance only for polymorphism benefits, never merely for the sake of inheriting properties.  Only use it when it is an elegant solution to a problem (such as the one described in my article Composition and recursive OCL) rather than as a way of avoiding having to enter the same attributes/behaviour on a new class.  Remember, just because a Building and a Person both have a name, a date of conception, and a location, doesn't make them the same thing!

 

Share this article!

Follow us!

Find more helpful articles: