In today’s article, I would like to talk about something which I see that, sometimes, developers aren’t too familiar with. Most of us know what the traditional concept of inheritance is: a child class extends a parent class. And, obviously, multiple children classes can extend the same parent class.
What some developers don’t seem to be always aware of (or, perhaps, they just aren’t entirely sure how to use it), is the idea of composition.
What is Composition
Composition can be explained by a child class “incorporating” one or more classes that it intends to extend. In other words, you are declaring inside your class, what other class’ methods do you want to be able to use, without having to strongly tie up your children class to its parent(s).
Has-a VS Is-a
A good way to look at Composition is to think of a class that HAS-A relationship with another class, rather IS-A “son” of that class. In this sense, when you use Composition, the class has an “identity” of its own, and it’s not to be seen as being “only” a son of that other class which it extends.
The Benefits of Composition
While I am not advocating for the complete elimination of traditional inheritance, there are benefits of using Composition that I would like to highlight. And, the way I see it, it is possible that once we realise the power of Composition over Inheritance, we may actually end up using Inheritance less and less. Here are the reasons why Composition is a good pattern:
- Flexibility: it is not by chance that I am giving this one the first position in my list. With Inheritance, as mentioned, you tie your Class up to another one, and you define even before starting to design your class, who is going to extend (be a child of) what. But, what happens if you wanted to only use some of the methods that your parent has? Or, on the opposite side, what if you had 5 children of which only 2 needed a couple of additional methods? These things would not have been a problem with Composition. But the truth is that Inheritance is often not flexible enough.
- Extension of Multiple Classes: who says you should only extend one Class? Why couldn’t
Corollabe a son of
Carbut also of
Toyotaat the same time? That obviously makes sense, but it’s normally not possible in traditional programming languages. Interfaces can give us some help here, but they don’t actually implement the methods we need.
- Avoid duplicates: Like in the previous example, if we were to use Interfaces for our
CorollaClass, we would end up having to write some of our methods for our
SedanClasses. That’s not cool. Duplicating code is not a good idea.
There are other benefits to using Composition, but those are the ones I feel are the most worthy of being highlighted here.
How do I use Composition in [insert programming language here]