Extract Class
Twice the class, half the mess.
“You have one class doing work that should be done by two.” – Martin Fowler
Split a class into two.
graph LR
A[Big Class] -->|Refactoring| B[Class 1]
A --> C[Class 2]
When to apply (Smells)
- Large Class: The class has too many fields/methods.
- Divergent Change: The class changes for different reasons.
Motivation
- Classes should follow the Single Responsibility Principle.
Mechanics (Steps)
- Decide how to split the responsibilities.
- Create a new class.
- Move fields and methods to the new class (using Move Field / Move Method).
- Reference the new class from the old one.
Explanation
Problem
One class does the work of two.
Solution
Create a new class and move the relevant fields and methods into it.
Real world analogy
You have a person who is both the Cook and the Waiter. Split them into two roles/people.
Pros and Cons
| Pros | Cons |
|---|---|
Comparison
- Inverse Refactoring: Inline Class.
Code example
Typescript
Before
After
PHP
Before
After