Recently I came across a programming convention called composition which is nowadays a preferable choice among developers over inheritance and in this article I would like to explore this convention using a small interactive funny example. Let’s begin.

So, here we are creating an enterprise-grade software for our client who demands to create a game which imitates the functions of a Man.

Pretty Simple demand huh…. And in a split of seconds, we create a Man class

# Class Man with functions eat, sleep, poop, lolClass Man .eat() .sleep() .poop()

We show this to our client and he is pretty impressed with our ability and speed of execution. Good Work he says.

But you should know with compliments come hidden demands.(evil smiley)

He wants us to add Dog to the game and make the man speak and dog bark.

We do it and this how our code looks like

Class Man .eat() .sleep() .poop() .speak()Class Dog .eat() .sleep() .poop() .bark()

We Show this to our client and he is happy and impressed but we are notbecause of all the repetition in the code and when we started our journey to programming, we have taken this sacred oath to keep our code DRY. So, we start thinking and go back to school where we learned inheritance.(the awww moment).

We decide to clean up the code and make it DRY by introducing an Animal Class and making Dog and Man class inherit Animal. So, all the common code goes to Base/Parent class Animal. Smart huh… Now, this is how our code looks like:

Class Animal .eat() .poop()Class Man < Animal .speak()Class Dog < Animal .bark()

Now, we are happy and our client is happy. Days pass by and one day our client come to us all excited and jumping to tell us his new brilliant idea. :D

He wants us to introduce a Cleaning Robot who will roam around and clean all the poop done by Man and Dog. And We do it in a split of a second.

Class CleaningRobot .roam_around() .clean()Class Animal .eat() .speak() .poop()Class Man < Animal .speak()Class Dog < Animal .bark()

Again, Everyone is happy and yet another requirement pops in (sighhhh). A Barking Dog Robot who will roam around and bark at Animals who try to poop in public places. This time we are now a professional programmer and we learn from our past mistakes and So, we follow inheritance in the first place and implement our logic for Barking Dog Robot by inheriting a Parent Class Robot in it. This is how our code looks like now:

bark()bark()

We give one look at a code and being a smart and experienced programmer we immediately sense a red flag in the code and can see future consequences if we keep following this pattern.

The bark() method is common in class BarkingDogRobot and Dog and somehow nothing fits in and if you remember we have taken an oath to keep our code Dry which keeps us bothering. :(

We can create a GameObject above all the classes something like below