Hello! Welcome back to another post on software engineering principles!

Let’s talk about why people say you should choose composition over inheritance.

What is it?

We all know what inheritance and composition are, so we’ll keep it short, just the parts that are relevant to us right now.

There are 2 ways in which you can reuse a component/code in your system:

By inheriting from it.

  ┌─────┐        
  │  A  │        
  └─────┘        
     ▲           
     │ inherits  
     │           
  ┌─────┐        
  │  B  │        
  └─────┘        

By having it as an attribute.

  ┌─────┐     has-a      ┌─────┐  
  │  B  │  ────────────► │  A  │  
  └─────┘                └─────┘  

This principle says that you should prefer the second way.

Why?

Because I said so :P haha. It’s because of coupling.

Let’s just see what happens if you inherit.

So imagine you are class B and you inherit from class A. Now, If there is ever a change in class A, you are affected. A change in one component necessitating a change in another component is called “high coupling”.

If you (again, pretend you are class B) instead, have class A as an attribute, you are not affected by changes in class A. Class A can be changed without having to change class B. This is low coupling. Now, of course, this assumes that you (class B) aren’t touching the internals of class A!

If you would just be so kind and take this just a little step further, instead of having an instance of class A, have an interface that class A implements!

  ┌─────┐     has-a       ┌──────────────────────────────┐  
  │  B  │  ────────────►  │ Interface that A implements  │  
  └─────┘                 └──────────────────────────────┘  

Now, B is very lowly coupled with A! The reason for this is that coupling to an interface is less coupling than coupling to a concrete class. So if you need to couple to something, try an interface! The underlying reason why coupling to an interface isn’t terrible is that interfaces rarely change!

I’m Still Not Satisfied!

Ok, ok. Here are some more benefits of composition over inheritance!

  • You have more flexibility because you can swap behavior at runtime simply by swapping the concrete instance or class that you are using. You can’t change what you inherit from at runtime! Hehe sucker.
  • You don’t run into the dreaded diamond inheritance problem. If you don’t know what that is, consider yourself lucky.
  • Deep inheritance hierarchies are hard to understand!

Conclusion

Ok, probably you’re favorite part of my posts:

Reusing a component via composition is better than reusing it via inheritance because inheritance leads to high coupling. Furthermore, composition gives you more flexibility (can swap behavior at runtime), avoids the diamond inheritance problem, and makes your code easier to understand (deep inheritance hierarchies are hard to understand).

That’s it! Hope you have an amazing day, and hope to see ya in the next one!