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)

  1. Decide how to split the responsibilities.
  2. Create a new class.
  3. Move fields and methods to the new class (using Move Field / Move Method).
  4. 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
  • Adheres to SRP
  • Easier to maintain
  • More files
  • Comparison

    • Inverse Refactoring: Inline Class.

    Code example

    Typescript

    Before

    After

    PHP

    Before

    After