Replace Delegation with Inheritance
You are using delegation and are writing many simple delegating methods to the entire interface of the delegate.
“You are using delegation and are writing many simple delegating methods.”
If it really IS-A, use inheritance.
graph LR
A[Class A] -->|Delegates| B[Class B]
A -->|Refactoring| B
A -.->|Inherits| B
When to apply (Smells)
- Method Explosion: You are forwarding every method.
Motivation
- Simplicity:
extendsgives you all methods for free.
Mechanics (Steps)
- Make the delegating class inherit from the delegate.
- Remove the delegate field.
Explanation
Problem
Employee contains Person and delegates getName, getAddress, getPhone, etc.
Solution
Employee extends Person.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Replace Inheritance with Delegation.
Code example
Typescript
Before
After
PHP
Before
After