Composition vs Inheritance
Inheritance is about what it is while composition is all about what it has or what it's ability is.In Inheritance we pre-define the architecture like parent class is inherited by sub classes and this sub class is inherited by another sub classes and this nesting continues the more nesting we have the more rigid is our code that is more harder to change and some times our code may get fragile that is if we change in parent class it may effect sub class in unexpected manner.For example I have a Base class Human
then three sub class young,old,adult
then we have inner sub class for each of them which could be male,female
.But how this inner classes or inheritance make our code rigid or harder to change in future let's understand this issue with an example.
In class base inheritance i have created three classes Human -> Young -> Male
The method of Young and Human class are available to Male class instance, this is what i mean the inheritance is all about what it is, we are predefine the relationship and there inheritance. Suppose in future we have certain requirement for which we need to change the inheritance flow to Human->Male->Young. Some time it is possible to do change like this, but i am sure that in near future it will break because tight coupling that is Young class depend on Human, Male class depend on Young class will definitely will create issue in future because as a human we cannot predict future, changes will be there so how to resolve this. My preference is composition. Composition focuses on what is the ability, for that to understand i have created two function. A man function return an a instance with sleep ability which is provided by getSleepAbility function. So dividing the requirement into ability and composing required abilities is the answer to tight coupling which is caused by what it is
instead of what ability it has
.
Top comments (0)