| rule_id | 72 |
|---|---|
| rule_category | general |
| title | Prefer composition over class inheritance |
| severity | 2 |
Inheritance creates a tight coupling between a base class and its derived classes. Any change to the base class can unexpectedly break derived classes, and the inheritance hierarchy can become difficult to understand as it grows. Composition — building behavior by combining small, focused objects or interfaces — avoids these problems.
Prefer composition when:
- The relationship is "has-a" rather than "is-a".
- You want to reuse behavior without exposing or depending on the internals of another class.
- You need to vary behavior at runtime (e.g. through the Strategy pattern).
Exception: Inheritance is appropriate when a true "is-a" relationship exists and when derived classes genuinely extend (rather than replace) the behavior of their base class. Always follow the Liskov Substitution Principle when using inheritance.