Favoring composition over inheritance is a principle that aligns well with maintainability, flexibility, and testability.
Let's break down the key points and thoughts on this:
Inheritance establishes an "Is-a" relationship between a base class and a subclass.
It's a quick and intuitive way to share attributes and behavior between classes.
The problem is that it is difficult to maintain.
- Subclasses depend on parent class implementation. It is hard to navigate.
- Subclasses inherit all parent class behaviors, even if they don't need them.
- Overriding parent class behavior can introduce bugs.
Composition forms a "Has-a" relationship.
The idea is to build more complex objects by combining simpler objects.
Components are reusable across different classes.
It's easy to change behavior at runtime by changing the components of a class.
Smaller, self-contained components are easier to change.
Components are independent and interact through well-defined interfaces, reducing their dependencies.
Pros of Composition:
Easy to Test individual components.
Components are easier to change.
You can swap components at runtime.
Promotes clean separation of concerns, adhering to the Single Responsibility Principle.
Cons of Composition:
Increase the number of objects in a system.
Managing dependencies and the interactions between components can be more complex than inheritance.
When do you Favor Composition?
Frequent Changes: In places where requirements change often, or new features are regularly added.
Component Reusability: When aiming to reuse components across different parts of the application or even different projects.
When do you Use Inheritance?
Stable Hierarchies: For foundational structures that are unlikely to change and where the relationship naturally fits an "is-a" model.
Shared Behavior: When multiple classes share a significant amount of behavior that makes logical sense to inherit.
As a general Rule:
Start with a composition-first approach in areas where you expect frequent changes or require high flexibility.
Use inheritance for foundational structures unlikely to change and where shared behavior across subclasses makes logical sense.
Favoring composition doesn’t mean inheritance is an obsolete concept.
Inheritance is still useful, especially when objects need to behave in a similar way.
But, in other words, Composition screams Modularity!
Don’t you think so?
Articles I enjoyed this week
How Instagram Scaled to 2.5 Billion Users by Neo Kim
Caching at Multiple Levels by Saurabh Dashora
Software Architecture Diagrams with C4 Model by
How to choose between batch, micro-batch, and streaming… by
Very well explained Raul!
I've also found composition to be far more useful in day-to-day stuff. The use of inheritance has been relatively less.
Thanks for the mention as well!