Composition vs. Inheritance

It’s Not Even a Fair Fight

The Startup
Published in
2 min readJul 16, 2019

--

Anyone who’s used an object oriented language in the past is probably familiar with the concept of inheritance, the idea of having child classes that inherit methods and instance variables from a parent class. Typically the relationship between a parent class and a child class is defined as an “Is A” relationship. In that the parent class defines a superset of its children. For example a parent class of fruit would have a child class of an apple because an Apple is a fruit. Here’s another example of that kind of relationship in code.

C#

Here we can see the BassetHound class inherits the Bark() method from the Dog class. Inheritance is great for reducing duplication in your code by allowing multiple child classes to inherit its methods. However that’s about where the benefits of inheritance ends because composition can do that and more!

Composition is the idea of defining pieces of functionality that can be used across multiple different classes without the need of a parent class. For example take an Airplane class and a Helicopter class, they both need to have the method of Fly(). When thinking in terms of inheritance you may think to create a parent class of Aircraft to hold the Fly() method. However what if you need to create a Canary class? Now you have a decision to make. Do you create another parent class that defines a relationship between Birds and Aircrafts? Do you just duplicate the fly method on both classes? Personally, neither of those sound like good options to me as they would both just muddy up our code.

This is why composition works so well. Composition allows you to define Fly() outside of Airplane, Helicopter or Canary and have them all be composed with Fly(). Composition defines a relationship type of “Has A” Like with an airplane, a helicopter, or a canary they all have the ability to fly. Here’s a similar example in code.

C#

In this example we created Fly() separately from any of our classes and then injected it into the creation of both our Airplane and our Canary. Not only does this reduce duplication but it also reduces any complication that would come with trying to implement similar functionality using inheritance. Using composition here also allows us to easily inject a mock of Fly() if we needed to for testing purposes.

In nearly every case, using composition is a better option as it provides all of the same benefits of inheritance, provides greater flexibility and more clarity over inheritance while also avoiding any of the downfalls with using inheritance.

So I hoped you learned something from this post and maybe even learned something. If you have any questions make sure to leave a comment down below. Thanks for reading!

--

--