Composition vs. Inheritance

Many others have covered this topic, but I don't agree to most of them. I wanted to capture my opinion about this dilemma here.

If you don't want to read the whole topic, the short answer to the dilemma under question is "it depends". If you prefer to find out all the details, then read on.

 

What's Composition?

Composition can be expressed as the following diagram:

In short, Client aggregates different interfaces because it depends on their functionalities. Don't get confused by the "Composition" term - Client class does not really compose interfaces.

 

What's Inheritance?

Now, let's see what Inheritance means in this context (well, we know what inheritance means, but anyway):

Client inherits from BaseClient, which in turn inherits from Base.

 

Context

People compare these two approaches when they are trying to design "Client" classes and find things that they think should belong to somewhere else, so that Client simply uses it as pre-existing capability. That's when the dilemma of "Composition vs. Inheritance" appears: should we put the common functionality in a separate interface, or should we put it in a base class?

I've often heard that composition is a better choice between the two, while in fact, it depends on the concrete situation. While I am trying to keep neutral position here, sometimes I feel so "sorry" for inheritance, that I start liking it more. After all, inheritance has (and always had) its purpose, and no one would ever use it if not its purpose and delivered value.

 

Making the Choice

Now, facts and rules for choosing the right strategy:

I hope you got the idea. I like both approaches, but I don't think any of them is better than the other one without specific context.

 

If you want to learn about composition, inheritance, and other object-oriented design principles, I would recommend taking a training course on this subject, delivered by myself.

 

About Author and Content

Author of the above content is Tengiz Tutisani - owner and technical leader at tutisani.com.

If you agree with the provided thoughts and want to make it part of your team's culture, we can help.
We provide in-person, immersive technical workshop training courses around Software Architecture, Domain-Driven Design, and Extreme Programming topics. We also develop software solutions.

Let's Talk!