Extract Interface
Several clients use the same subset of a class’s interface.
“Several clients use the same subset of a class’s interface, or two classes have part of their interfaces in common.”
Decouple implementation from contract.
graph LR
A[Class A] -->|Refactoring| B[<Interface I>]
A -.->|Implements| B
When to apply (Smells)
- Coupling: Clients depend on the whole class when they only need a few methods.
Motivation
- De-coupling: Clients can depend on
Billableinstead ofEmployee.
Mechanics (Steps)
- Create an interface.
- Make the class implement it.
- Change type annotations in clients to use the interface.
Explanation
Problem
Company depends on Employee but only uses getRate() and hasSpecialSkill().
Solution
Create Billable interface with getRate() and hasSpecialSkill().
Pros and Cons
| Pros | Cons |
|---|---|
Code example
Typescript
Before
After
PHP
Before
After