Replace Inheritance with Delegation
A subclass uses only a small part of its superclass or does not inherit its “is-a” relationship.
“A subclass uses only a small part of its superclass or does not inherit its ‘is-a’ relationship.”
Favor Composition over Inheritance.
graph LR
A[Subclass] -.->|Inherits| B[Superclass]
A -->|Refactoring| B
A -->|Delegates| B
When to apply (Smells)
- Refused Bequest: Inheriting unwanted methods.
- Liskov Substitution Principle Violation: Subclass doesn’t behave like superclass.
Motivation
- Clean interface: Expose only what is needed.
Mechanics (Steps)
- Create a field in the subclass that reference the superclass.
- Change inheritance to delegation (remove
extends). - Forward calls to the delegate.
Explanation
Problem
Stack extends Vector. Stack shouldn’t have insertAt(i).
Solution
Stack contains a Vector. Stack methods call Vector methods.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Replace Delegation with Inheritance.
Code example
Typescript
Before
After
PHP
Before
After