
Favoring Delegation over Inheritance
One of the most sensible principles in the GoF tome is to
favor composition over inheritance or, as Gamma, Helm, Johnson, and Vlissides put it:
Favor object composition over class inheritance
Object composition is an alternative to inheritance. However, they point to a very precise kind of inheritance that causes most of the problems they’re talking about. For example, suppose we have a car object and we want a navigation system for it. The approach that GoF is concerned about is where the developer creates a subclass of the car object to include a navigation system or create a navigation subclass with added car functionality. Figure 1 shows the approach to inheritance they argue leads to tight coupling:

Figure 1: Inheritance solutions to adding navigation
After using composition this kind of inheritance may seem heavy-handed, but it is the kind of reuse that Gamma,
et al, are suggesting that is better handled by composition. GoF use an example of a
Window object (a regular glass window—not one that Bill G. owns) obtaining a rectangle shape by becoming a subclass of a
Rectangle class. In that way, the Window
is a rectangle. The logic is that, since you have a rectangle anyway and windows are rectangles, just make a subclass of Rectangle and give it Window properties. In that way, you reuse all of the rich functionality of the rectangle without having to re-invent it in a new Window class independent of the Rectangle class. (Turn the page to find out more about composition and delegation.)
Read more…
Recent Comments