Favor Composition over Inheritance

Purpose:

Encourage the use of object composition instead of inheritance for code reuse and flexibility. Composition allows building more adaptable and maintainable systems by combining smaller, independent components rather than relying on rigid inheritance structures.

Key Idea:

Inheritance leads to tight coupling between parent and child classes, reducing flexibility. Composition, on the other hand, enables loose coupling by allowing objects to be composed of smaller, reusable components, improving code modularity and maintainability.

Use Case:

When building a system, consider creating small, reusable components that can be combined to achieve functionality instead of extending base classes. For example, instead of inheriting from a class to add logging, inject a logging component through composition.


Backlinks