One of the fundamental activities of any software system design is establishing relationships between classes. The two fundamental ways to relate classes are inheritance and composition.
Quite often the most common approach to gain access to class members and methods of a class is to extend the class. This is mainly due to the fact when we are introduced OO programming one of the main themes that most people get very excited about is inheritance. But using extends without careful consideration could be costly. Quite often the relationship between your classes is more suited for composition (i.e. a “has-a” relationship).
I remember when I was creating a cards game application; I needed access to players object in the canvas and mechanically just extended the players. Composition in that instance would have the correct approach to choose.
| Inheritance: advantages | Inheritance: disadvantages |
| + Dynamic binding (i.e. allowing the JVM to decide at runtime which method implementation to invoke). When used in the right place the prime benefit of dynamic binding is that the code becomes much easier to change.
+ Polymorphism (capability of holding superclass or any of its subclasses) |
– Superclasses are considered to be “fragile”; incorrect use of extends and one little change to a superclass can ripple down and require changes in many other places in the application’s code. |
| Composition: advantages | Composition: disadvantages |
| + Provides stronger encapsulation because a change to a back-end class needn’t break any code that relies only on the front-end class. | – The explicit method-invocation forwarding (or delegation) MIGHT have a performance cost as compared to inheritance’s single invocation.
– The bigger downside is that is that it is not as light-weight in Java. |
To Summarize:
One thing to consider is that if your goal is code reuse think composition as it provides a better approach that yields easier-to-change code. Don’t use inheritance just to get code reuse. An important question to ask yourself when you think you have a “is-a” relationship is whether that “is-a” relationship will be constant throughout the lifetime of the application and, with luck, the lifecycle of the code.
In general, over the years I become to favour composition over inheritance. I’ve seen too many projects; some of my own; get incredibly and unnecessarily confusing due to complicated inheritance hierarchies so deep that will make your eyes water. However, there are some cases where inheritance simply makes more sense logically and programmatically. These are typically the cases where an object has been broken into so many subcomponents that it doesn’t make sense any more as an object itself.
Joshua Bloch Nugget: Design and document for inheritance or else prohibit it. When designing for inheritance you are committing FOREVER to the self-use patterns.

Leave a comment