Software Engineers Notebook

Software Engineering notes to myself that you may find useful too

View on GitHub
18 September 2018

Composition vs Inheritance

by Martyn Butterworth

Composition and inheritance class diagram

So how exactly do composition and inheritance compare? Here are several points of comparison:

Choosing between composition and inheritance

So how do all these comparisons between composition and inheritance help you in your designs? Here are a few guidelines that reflect how I tend to select between composition and inheritance.

Make sure inheritance models the is-a relationship. The main guiding philosophy is that inheritance should be used only when a subclass is-a superclass. For example, an Apple likely is-a _Fruit, so I would be inclined to use inheritance. An important question to ask yourself when you think you have an _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. For example, you might think that an Employee is-a Person, when really Employee represents a role that a Person plays part of the time. What if the person becomes unemployed? What if the person is both an Employee and a Supervisor? Such impermanent is-a relationships should usually be modeled with composition.

Don’t use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.

Don’t use inheritance just to get at polymorphism If all you really want is polymorphism, but there is no natural is-a relationship, use composition with abstract classes.

tags: