Composition Over Inheritance

You can’t add the flying ability to the Human class because not all humans can fly, and you can’t make the teacher inherit from the EvilDragon class, because the teacher can’t breathe fire.

There is a solution: it’s to add features, like breathing fire, that will never be used by the teacher object to make him able to fly.

However, this is like asking for a banana and receiving a gorilla holding a banana.

So now you’ve hit a wall, and now you can’t turn your game idea into a reality.

Of course, you can repeat yourself, but since you’re an excellent developer who cares about every line of code you write, you won’t do that.

Don’t worry, there’s a solution: It’s called Composition.

With inheritance, you structure your classes around what they are.

With composition (and functional programming), you structure your classes on what they do.

By favoring composition over inheritance and thinking in terms of what things do rather than what things are, you free yourself of fragile and tightly coupled inheritance structures.

Here’s a snippet of what our code might look like in our game when we think in terms of objects:When we write our project using a functional approach, we end up with a collection of stand-alone functions, each one of them serving a single purpose, which facilitates maintainability and makes debugging easier since we can predict the outcome of a function.

When creating an object, we simply import all the functions that we need.

Which one wins?.Well, normally you would use inheritance when there is a relation between objects, like me, Mahmoud, I’m a human, so I will inherit all of the things that a Human has.

On the other hand, you would use composition, for example, when an object has a certain feature like, for example, a Car will have an engine component.

However, this is not completely true because a car is a vehicle and I, Mahmoud, have arms and I can lift things.

So, in reality, you can follow either of these patterns.

Like most things in engineering, it depends.

Composition or inheritance, you have to think about your codebase, your team, the feature you’re working on and where it could all go in the future.

Choose the right tool for the job.

ResourcesComposition (Wikipedia)Inheritance (Wikipedia).. More details

Leave a Reply