Composition Over Inheritance
Mohamed G.Hafez
Posted on July 18, 2022
I will go to the journey with you to explain some design principles to help us to organize, clean our codebase and make it more extendable and maintainable. So let's go with important concept which make our code cleaner and reusable.
What is the composition and when we should use it?
Let me explain and answer this question by example, we all love examples :)
Imagine you have super class called Duck
class Duck
{
public function fly(){}
public function quack(){}
public function display(){}
}
This class has 3 normally methods and it's good for now and it works well for us until your client request a new type of duck to be added called RubberDuck, here you will notice the problem ?
Lets see the problem
class RubberDuck extends Duck
{
public function fly(){} // Why implement this method ?!
public function quack(){} // also why too ?!
public function display(){}
}
when you extend from parent Duck class you will inherit a method called fly() and Quack() which are useless to Rubber Duck so what is the solution ? The answer will be to pull out the fly and Quack methods outside Duck class and make a new interface called something like FlyableInterface and QuackablInterface which both have one method for example called fly() at FlyableInterfance and quack at QuackablInterface after that the Duck class can implement these interfaces methods based on its function
so the code will be refactored to
Interface Flyable
{
public function fly();
}
Interface Quack
{
public function quack();
}
Now the new version of RubberDuck class will implement the new interface method
class RubberDuck implements FlyableInterface, QuackableInterface
{
public function fly(){} // from interface
public function quack(){} // from interface
public function display(){}
}
and the Duck class has one method which in common for all types called display()
class Duck
{
public function display(){}
}
so here we partially solve the problem but we will notice some problems also after this update but let's discuss that in other articles or write your comments about the problems.
So from the example above we can summarize the meaning of composition by saying it's a process to pull out some methods outside the class and create the interfaces to enable the that class implement the suitable interfaces methods not every method from the super class.
I hope that I succeeded in clarifying the idea, even in a simple way.
Thanks for your reading and sorry for my english as it's not my tongue language
Posted on July 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024