Skip to content

Extract Class: Split a Class That Does Two Jobs

Learn how to use Extract Class to move one responsibility out of an overloaded class into its own class, in small steps with tests passing throughout.

7 min readRefactoring

Extract Class takes a group of fields and the methods that work on them out of one class and gives them a home of their own. The original class keeps a reference to the new one and asks it for help instead of doing the work itself. This guide walks through the refactoring on an invented rental platform, Larkspur Lettings, where a Tenant class has quietly turned into two classes sharing one name. You will see the code before and after in TypeScript, Python and PHP, the safe sequence of steps, and how to talk about the trade-offs in an interview.

The problem

A situation where the obvious design starts to hurt.

At Larkspur Lettings, Tenant started as a record of who lives in which unit. Then the deposit-protection rules arrived, and someone added depositCents, depositHeldMonths and depositRateBp along with interest and refund calculations.

Now the class has two reasons to change. A tweak to how tenants are described touches the same file as a change to deposit interest law. The three deposit fields always travel together and share a deposit prefix, which is a strong hint that they describe a concept the code has not named yet. Testing the refund rule means building a whole tenant with a name and a unit, even though neither affects the result.

Before and after

The same code, before and after the change.

Before

class Tenant {
  constructor(
    readonly name: string,
    readonly unit: string,
    readonly monthlyRentCents: number,
    readonly depositCents: number,
    readonly depositHeldMonths: number,
    readonly depositRateBp: number,
  ) {}

  describe(): string {
    return `${this.name} (unit ${this.unit})`;
  }

  depositInterestCents(): number {
    // simple annual interest, rate in basis points, rounded down
    return Math.floor(
      (this.depositCents * this.depositRateBp * this.depositHeldMonths) / 120000,
    );
  }

  depositRefundCents(damageCents: number): number {
    return Math.max(0, this.depositCents + this.depositInterestCents() - damageCents);
  }
}

const tenant = new Tenant("Mara Okafor", "4B", 145000, 290000, 18, 150);
console.log(tenant.describe()); // Mara Okafor (unit 4B)
console.log(tenant.depositRefundCents(12000)); // 284525

After

class SecurityDeposit {
  constructor(
    readonly amountCents: number,
    readonly heldMonths: number,
    readonly rateBp: number,
  ) {}

  interestCents(): number {
    // simple annual interest, rate in basis points, rounded down
    return Math.floor((this.amountCents * this.rateBp * this.heldMonths) / 120000);
  }

  refundCents(damageCents: number): number {
    return Math.max(0, this.amountCents + this.interestCents() - damageCents);
  }
}

class Tenant {
  constructor(
    readonly name: string,
    readonly unit: string,
    readonly monthlyRentCents: number,
    readonly deposit: SecurityDeposit,
  ) {}

  describe(): string {
    return `${this.name} (unit ${this.unit})`;
  }
}

const tenant = new Tenant("Mara Okafor", "4B", 145000, new SecurityDeposit(290000, 18, 150));
console.log(tenant.describe()); // Mara Okafor (unit 4B)
console.log(tenant.deposit.refundCents(12000)); // 284525

Why it's worth it

What the change buys you.

A class should have one reason to change. Before the refactoring, Tenant changed whenever occupancy details changed and whenever deposit rules changed, and the two sets of members never touched each other: describe uses no deposit field, and the deposit methods use no tenant field. That clean split in data usage is the clearest signal that Extract Class is the right move.

After the split, SecurityDeposit names a real domain concept. Its fields lose the repeated deposit prefix because the class itself provides the context. You can test refund rules by constructing a three-field object instead of a full tenant, and the next legal change to interest calculation lands in a small file with no unrelated code around it.

The calculation itself is untouched. The integer arithmetic, the floor division and the clamp at zero are moved character for character, so every input produces the same output as before.

  • Each class has a single reason to change: tenant details or deposit rules.
  • Deposit logic can be unit tested without inventing a name, unit or rent.
  • The three deposit values travel as one named object instead of a loose clump of integers.
  • Field names get shorter and clearer because the class name carries the context.
  • New deposit behaviour, such as partial refunds, has an obvious home.

Careful with

  • Do not extract a class just because a file is long. Look for a subset of fields and methods that use each other and ignore the rest; if everything references everything, the split will create chatty coupling.
  • Exposing tenant.deposit publicly can invite callers to reach through chains of objects. If that starts happening, keep narrow delegating methods on Tenant instead.
  • If the extracted object is mutable and shared, two tenants could end up pointing at the same deposit. Keep it immutable or create a fresh instance per owner.
  • Persistence layers and serializers often map fields by name. Check ORM mappings and API payloads before renaming or nesting the moved fields.

Step by step

Small, safe steps, with the tests passing after each.

  1. Make sure tests cover describe, depositInterestCents and depositRefundCents, including a refund where damage exceeds the deposit and returns 0. Run them green.

  2. Create an empty SecurityDeposit class next to Tenant. Nothing uses it yet, so tests still pass.

  3. Give SecurityDeposit a constructor taking amount, held months and rate. Inside Tenant's constructor, build a private SecurityDeposit from the three existing deposit fields. Run tests.

  4. Move depositInterestCents into SecurityDeposit as interestCents, using its own fields. Leave Tenant.depositInterestCents as a one-line delegator to it. Run tests.

  5. Move depositRefundCents the same way, as refundCents, keeping a delegator on Tenant. Run tests.

  6. Expose the deposit object as tenant.deposit and update callers one at a time to call tenant.deposit.refundCents(...), running tests after each batch.

  7. Once no caller uses the delegators or the old depositCents, depositHeldMonths and depositRateBp fields, delete them from Tenant.

  8. Change Tenant's constructor to accept a SecurityDeposit instead of three primitives, update construction sites, and run the full suite.

Smells it removes

Smells this refactoring helps remove.

Common questions

Short answers to the usual doubts.

How do I know a class is doing two jobs?

Group its fields by which methods read them. If one cluster of methods only touches one cluster of fields and another cluster only touches the rest, you have two classes. Shared name prefixes, like deposit here, and change requests that only ever touch one cluster are further evidence.

Should the original class keep delegating methods after the extraction?

It depends on who calls them. Temporary delegators are useful during migration so you can move callers gradually. Keep them permanently only when you want to hide the new class from callers; otherwise remove them so Tenant does not become a middle man.

What is the opposite refactoring?

Inline Class. If an extracted class ends up with almost no behaviour and only one user, fold it back into that user. The two refactorings are tools for moving the boundary in either direction until each class earns its place.

How is Extract Class different from Extract Superclass?

Extract Class uses composition: the original class holds a reference to the new one. Extract Superclass uses inheritance to share behaviour between similar classes. A tenant has a deposit rather than being one, so composition is the right fit here.

How would I explain this refactoring in an interview?

Name the smell, show the split in field usage, then describe the safe sequence: create the class, move fields, move methods one at a time with delegators, migrate callers, delete the leftovers. Mention that tests pass after every step and that behaviour is unchanged, which shows you can restructure production code without a risky big-bang rewrite.

Next guide3 of 5 · Techniques: moving featuresInline Class: Fold a Class That No Longer Earns Its KeepRead the next one