Why composition is better than inheritance?

The problem of inheritance: Superclass and Sub Class can have some properties and methods, but what if we change some properties and methods in the Superclass. There is a problem called tight coupling. Classes and objects created through inheritance are tightly coupled because changing the parent or superclass in an inheritance relationship risks breaking your code. it is definitely the opposite of reusable modular code. Also, subclasses are using inheritance this concept leads to the other problem it is called the fragile base class problem. The fragile base class problem is a fundamental architectural problem of object-oriented programming systems where base classes (superclasses) are considered “fragile” because seemingly safe modifications to a base class, when inherited by the derived classes, may cause the derived classes to malfunction.

Inheritance concept is everything becomes too tight a couple where eventually as a program gets bigger and bigger. It creates more and more issues. You start violating the dry principle of do not repeat yourself.

In other words, Inheritance is a superclass that is extended to small pieces that add or overwrite things. That is inheritance and although you can be careful with it and making sure that the base class is very general so that we do not overload subclasses. It can easily get out of hand as we go deeper and deeper down the inheritance chain. Also, once we need to change some properties and methods it becomes really difficult.

The Concept of composition is about smaller pieces that are combined to create something bigger. we combined the boxes based on what we need to create our desired output and if we need to add something later on while we just add another by composing things together, or we add another box and composing things, or you can remove them if we do not need them anymore. Composition solution gets popular than Inheritance. However, this does not mean that inheritance is always bad. There are ways that you can still write great code with inheritance, but the problem that might come up in the future especially with so many unknowns and humans unable to predict the future, and all the changes that we might need to make to a program it becomes complicated. So composition is also an excellent solution for us to use to keep in mind. It is going to help us create code that is more stable as well as easier to change in the future.

Leave a Reply

Your email address will not be published.

ANOTE.DEV