DEV Community

Tien Do
Tien Do

Posted on

Rethinking the "Composition over Inheritance" principle : When Software Engineers should abandon it?

  • The statement "Composition over Inheritance" is a widely accepted principle in object-oriented programming, but is it always the best approach? While composition does offer more flexibility and modularity, there are situations where inheritance can be a better option. It all depends on multiple factors, such as the complexity of the object hierarchy, the amount of code reuse required, and how we want to model our objects in the real world, which is the point I want to elaborate in this post.

  • First, let's talk about the purpose of using inheritance in the first place. There are many different benefits, and here is one of them, it is a powerful feature of object-oriented programming languages that allows us as developers to create a clear and concise representation of the relationships between different objects. Using it, we can define a base class that contains common properties and behaviors and then let the sub/children classes inherit from that base class to create more specialized features. This reduces the need to duplicate code and makes it easier to maintain and update it over time.

  • Secondly, this clear and concise representation of the natural world objects is important because it makes our code base easier to read and understand. At the same time, we can use composition to make it loosely coupled. Still, everything has trade-offs in software engineering, and the trade-off we make here is the question that other fellow developers will likely ask, "Why do we not just use inheritance here?" that can lead to more confusion when our team scales in the future.

  • Finally, the principle is just a guideline, and we need to understand why we use it to know when we should use it and when not. Just because the majority widely accepts this principle doesn't mean we should apply it everywhere in our codebase. Otherwise, what is the point of critical thinking and creative problem-solving in software engineering?

  • I have attached two trivial examples to illustrate my point. Let me know what you think in the comment section. Or reply to this intriguing question, "What are the other scenarios you think we should prefer inheritance over composition?"

Image description

Latest comments (0)