Composition VS Inheritance in stack’s implementation


To prefer composition over inheritance was the choice of many people I happen to learn a lot from, In many cases, it sounded natural and made sense.

With composition, you ensure single responsibility and loosely coupled components of your software.

Composition VS Inheritance

However, if we think that inheritance means “Is A” and composition means “Has A”, It’s very hard in many cases to say that a Doctor has a Person instead of saying a Doctor is a person, I tried but I couldn’t do it.

Anyway, I’m here for a different reason, I’m here to talk about an example when I had to choose between composition and inheritance and why did I favor one over the other.

When I started using dart it originally had no stack implementation, I decided to create it (Give it a look here) and I would need to re-use the functionality of the list class in Dart.

Inheritance way

Let’s see, can I say that a stack is a list? maybe, I wouldn’t say that in an exam as well as on any other occasion but let’s say I will let that pass and consider a stack as a list with slightly different behavior.

If we inherited the list we give our stack all the functionality that exists in a normal list, your stack now can be used to achieve FIFO (first in, first out) behavior, which my friend I will not let pass.

If we insist to use inheritance we will need to override all the functionality we don’t want to expose and throw some kind of exception every time someone is trying to access them.

Won’t begin to count how many principles of clean code or clean architecture you’re breaking here, but don’t worry, because people from oracle seem to have done it in their stack implementation in Java

Composition way

On the other hand, we can say that a stack has a list, yeah that’s true, a stack has a list that is private and can’t be accessed from outside the stack, your push and pop operations affect it and therefore affect the state of your stack.

There is no functionality that is exposed without you adding it, It’s just the stack-related functionality.

And yes, This is how I decided to implement my stack package in Dart, does it feel natural to you as well?


Leave a Reply

Your email address will not be published. Required fields are marked *