39

Extract Class


Goal

A cohesive sub-concept inside a class becomes its own class with its own name, fields, and methods.

Before the refactoring
class Person {
  name;
  officeAreaCode;
  officeNumber;
  telephoneNumber() { return `(${this.officeAreaCode}) ${this.officeNumber}`; }
}
After the refactoring
class Phone {
  areaCode;
  number;
  toString() { return `(${this.areaCode}) ${this.number}`; }
}
class Person { name; phone; }
Savings

Each class has one purpose; tests target the small unit; the parent class shrinks.

Note

Premature class extraction adds ceremony — extract when 3+ fields and at least one operation cluster around a single concept that the parent class doesn't own.