Composition over Inheritance?

Umangshrestha
Geek Culture
Published in
5 min readJul 20, 2021

--

Composition vs. Inheritance. Why prefer composition over inheritance?

Composition over inheritance is a principle in object-oriented programming that suggests prioritizing the use of composition to achieve polymorphic behavior and code reuse, instead of relying heavily on class inheritance. While inheritance allows a class to inherit properties and behaviors from a parent class, composition focuses on constructing complex objects by combining simpler objects.

Inheritance has the strength of establishing a hierarchical structure, enabling code reuse, and defining common behavior among related classes. It provides a way to organize and categorize objects based on shared characteristics. However, it can lead to tight coupling and limited flexibility due to the limitations of single inheritance.

On the other hand, composition offers several advantages. It promotes loose coupling and flexibility by allowing objects to be constructed from different components. It encourages the use of interfaces or protocols to define behaviors that can be implemented by multiple classes. Composition enhances modularity and facilitates easy modification or extension of objects by adding or replacing components.

The saying “Favor object composition over class inheritance” suggests that, in many scenarios, the composition can be a more flexible and maintainable approach. By leveraging composition, code can be structured to encourage reuse, modularity, and polymorphic behavior. Programming languages like GO…

--

--

Umangshrestha
Geek Culture

I like computer and programming. I am currently trying to learn how to write articles for sharing what I know.