extract-class
Split a class that holds too many responsibilities into two focused classes.
SKILL.mdskills/code-quality/extract-class/SKILL.md
GitHubExtract Class
A class that has grown beyond its original purpose accumulates fields and methods that belong to a distinct concept. Extract them into a new class.
When to Use
- Class has more than one reason to change (violates SRP)
- A subset of fields/methods are always used together
- A natural sub-concept emerges when describing the class
- Class name no longer accurately describes its full responsibility
How to Apply
- Identify the cohesive subset of fields and methods to extract
- Create the new class with a meaningful name
- Move the fields first (update references in old class via the new object)
- Move the methods one by one; run tests after each move
- Decide the visibility (public field or private with accessor)
- Run tests
Example
// Before
class Person {
name: string;
officeAreaCode: string;
officeNumber: string;
telephoneFor() { return `(${this.officeAreaCode}) ${this.officeNumber}`; }
}
// After
class TelephoneNumber {
areaCode: string;
number: string;
toString() { return `(${this.areaCode}) ${this.number}`; }
}
class Person {
name: string;
office = new TelephoneNumber();
telephoneFor() { return this.office.toString(); }
}