Favor composition over inheritance

Inheritance of classes is not always a good idea, sometimes you need to consider the composition as well.

Let's discuss one of the important design principles, for writing more clean, reusable, and extensible code -

Suppose you are running a vehicle company that makes Cars and Trucks.

The first thought that comes to mind while designing the classes for such use cases is to have -
1 superclass - vehicle
2 subclasses - car, truck

There is nothing wrong with this approach it is the right way to do things, but as a growing company you started to see opportunities in the EVs and decided to start the EV car and after a few months EV truck as well.

And who knows what the future holds, there are endless possibilities to come, and looking to break our code in many ways.

There’s an alternative to inheritance called composition.

Whereas inheritance represents the “is a” relationship between classes (a car is a transport).

composition represents the “has a” relationship (a car has an engine).

To avoid the combinatorial explosion of classes we can make use of, different “dimensions” of functionalities to extract to their class hierarchies.

This way we can make things simpler, and the code architecture becomes so much more user-friendly, and clean, with the ability to add new functionalities in the future without breaking the previously written classes.

0
Subscribe to my newsletter

Read articles from Atharva Mahamuni directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Atharva Mahamuni
Atharva Mahamuni

Writing about the software development