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)); // 284525class Tenant:
def __init__(
self,
name: str,
unit: str,
monthly_rent_cents: int,
deposit_cents: int,
deposit_held_months: int,
deposit_rate_bp: int,
) -> None:
self.name = name
self.unit = unit
self.monthly_rent_cents = monthly_rent_cents
self.deposit_cents = deposit_cents
self.deposit_held_months = deposit_held_months
self.deposit_rate_bp = deposit_rate_bp
def describe(self) -> str:
return f"{self.name} (unit {self.unit})"
def deposit_interest_cents(self) -> int:
# simple annual interest, rate in basis points, rounded down
return self.deposit_cents * self.deposit_rate_bp * self.deposit_held_months // 120_000
def deposit_refund_cents(self, damage_cents: int) -> int:
return max(0, self.deposit_cents + self.deposit_interest_cents() - damage_cents)
tenant = Tenant("Mara Okafor", "4B", 145_000, 290_000, 18, 150)
print(tenant.describe()) # Mara Okafor (unit 4B)
print(tenant.deposit_refund_cents(12_000)) # 284525<?php
final class Tenant
{
public function __construct(
public readonly string $name,
public readonly string $unit,
public readonly int $monthlyRentCents,
public readonly int $depositCents,
public readonly int $depositHeldMonths,
public readonly int $depositRateBp,
) {}
public function describe(): string
{
return "{$this->name} (unit {$this->unit})";
}
public function depositInterestCents(): int
{
// simple annual interest, rate in basis points, rounded down
return intdiv($this->depositCents * $this->depositRateBp * $this->depositHeldMonths, 120000);
}
public function depositRefundCents(int $damageCents): int
{
return max(0, $this->depositCents + $this->depositInterestCents() - $damageCents);
}
}
$tenant = new Tenant('Mara Okafor', '4B', 145000, 290000, 18, 150);
echo $tenant->describe(), PHP_EOL; // Mara Okafor (unit 4B)
echo $tenant->depositRefundCents(12000), PHP_EOL; // 284525After
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)); // 284525class SecurityDeposit:
def __init__(self, amount_cents: int, held_months: int, rate_bp: int) -> None:
self.amount_cents = amount_cents
self.held_months = held_months
self.rate_bp = rate_bp
def interest_cents(self) -> int:
# simple annual interest, rate in basis points, rounded down
return self.amount_cents * self.rate_bp * self.held_months // 120_000
def refund_cents(self, damage_cents: int) -> int:
return max(0, self.amount_cents + self.interest_cents() - damage_cents)
class Tenant:
def __init__(
self,
name: str,
unit: str,
monthly_rent_cents: int,
deposit: SecurityDeposit,
) -> None:
self.name = name
self.unit = unit
self.monthly_rent_cents = monthly_rent_cents
self.deposit = deposit
def describe(self) -> str:
return f"{self.name} (unit {self.unit})"
tenant = Tenant("Mara Okafor", "4B", 145_000, SecurityDeposit(290_000, 18, 150))
print(tenant.describe()) # Mara Okafor (unit 4B)
print(tenant.deposit.refund_cents(12_000)) # 284525<?php
final class SecurityDeposit
{
public function __construct(
public readonly int $amountCents,
public readonly int $heldMonths,
public readonly int $rateBp,
) {}
public function interestCents(): int
{
// simple annual interest, rate in basis points, rounded down
return intdiv($this->amountCents * $this->rateBp * $this->heldMonths, 120000);
}
public function refundCents(int $damageCents): int
{
return max(0, $this->amountCents + $this->interestCents() - $damageCents);
}
}
final class Tenant
{
public function __construct(
public readonly string $name,
public readonly string $unit,
public readonly int $monthlyRentCents,
public readonly SecurityDeposit $deposit,
) {}
public function describe(): string
{
return "{$this->name} (unit {$this->unit})";
}
}
$tenant = new Tenant('Mara Okafor', '4B', 145000, new SecurityDeposit(290000, 18, 150));
echo $tenant->describe(), PHP_EOL; // Mara Okafor (unit 4B)
echo $tenant->deposit->refundCents(12000), PHP_EOL; // 284525Why 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.depositpublicly can invite callers to reach through chains of objects. If that starts happening, keep narrow delegating methods onTenantinstead. - 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.
Make sure tests cover
describe,depositInterestCentsanddepositRefundCents, including a refund where damage exceeds the deposit and returns 0. Run them green.Create an empty
SecurityDepositclass next toTenant. Nothing uses it yet, so tests still pass.Give
SecurityDeposita constructor taking amount, held months and rate. InsideTenant's constructor, build a privateSecurityDepositfrom the three existing deposit fields. Run tests.Move
depositInterestCentsintoSecurityDepositasinterestCents, using its own fields. LeaveTenant.depositInterestCentsas a one-line delegator to it. Run tests.Move
depositRefundCentsthe same way, asrefundCents, keeping a delegator onTenant. Run tests.Expose the deposit object as
tenant.depositand update callers one at a time to calltenant.deposit.refundCents(...), running tests after each batch.Once no caller uses the delegators or the old
depositCents,depositHeldMonthsanddepositRateBpfields, delete them fromTenant.Change
Tenant's constructor to accept aSecurityDepositinstead 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.