Object-oriented – “Prefer composition over inheritance” – Is the only reason to defend against signature changes

compositioninheritanceobject-oriented

This page advocates composition over inheritance with the following argument (rephrased it in my words):

A change in the signature of a method of the superclass (which hasn't
been overridden in the subclass) causes additional changes in many
places when we use Inheritance. However, when we use Composition, the
required additional change is only at a single place: The subclass.

Is that really the only reason to favor composition over inheritance? Because if that's the case, this problem can be easily alleviated by enforcing a coding style which advocates overriding all methods of the superclass, even if the subclass does not change the implementation (that is, putting dummy overrides in the subclass). Am I missing something here?

Best Answer

I like analogies so here's one: Have you ever seen one of those TVs that had a VCR player built-in? How about the one with a VCR and a DVD player? Or one that have a Blu-ray, DVD and VCR. Oh and now everyone is streaming so we need to design a new TV set...

Most likely, if you own a TV set, you don't have one like the above. Probably most of those have never even existed. You most likely have a monitor or set that has numerous inputs so that you don't need a new set every time there is a new type of input device.

Inheritance is like the TV with the VCR built-in. If you have 3 different types behaviors you want to use together and each has 2 options for implementation, you need 8 different classes in order to represent all of those. As you add more options the numbers explode. If you use composition instead, you avoid that combinatorial problem and the design will tend to be more extensible.

Related Topic