RSS Feed

RSS

Composition vs Inheritance

I’ve seen this asked many times. These models are not competing.

A good way of understanding composition and inheritance is by viewing them as completely orthogonal options. Inheritance grows features down and composition grows features sideways.

The traditional object model needs to be abstracted just a bit more to fit both composition and inheritance. So is now, that this new object model is composed of several components, each of which can have its own inheritance hierarchy.

A vehicle object can now be a group of components: tires, chasis, motor and transmission. And each component can be featured with inheritance: tires -> racing tires, motor -> turbo motor, etc.

As you can see, composition and inheritance are not mutually exclusive. Experience will help you better define blurry-overlapping models, making you better at identifying what should be a component and what should be inherited.

Similar projects with different depths can easily influence the design. For example a racing simulator may require in components what an arcade racing game would implement inherited. Again, only experience will help you define these models.