One class, one job
Spot a class that does too much and split it.
One reason to change
A class should change for one reason only. If pricing rules, spot search and receipt printing all live in ParkingLot, a change to any of them touches the same file and can break the others.
Ask: if I describe this class, do I need the word "and"? "Finds spots and computes fees and prints receipts" is three classes.
Split by responsibility
Move each job into its own class and let the main class coordinate. The coordinator stays short and readable; each helper can be tested alone.
class ParkingLot {
constructor(
private readonly spots: SpotFinder,
private readonly pricing: PricingPolicy,
) {}
leave(ticket: Ticket, time: number) {
this.spots.release(ticket.spotId);
return this.pricing.fee(ticket, time);
}
}
Key takeaways
- One reason to change per class.
- If the description needs "and", split it.
- A short coordinator plus focused helpers is easier to test and change.
Hands-on coding exercise
An order's total is its items plus 18% tax, with tax rounded down to a whole number.
Give tax its own class, so a tax change never touches Order. Order takes the calculator in its constructor.
class TaxCalculator {
/** 18% of the amount, rounded down */
tax(amount: number): number {
throw new Error("Not implemented");
}
}
class Order {
constructor(private readonly items: { price: number; qty: number }[], private readonly taxes: TaxCalculator) {}
subtotal(): number {
throw new Error("Not implemented");
}
total(): number {
throw new Error("Not implemented");
}
}
Run your solution against 4 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- A Library class validates members, computes fines, sends emails and stores books. What is the main problem?
- What does splitting a big class mainly buy you?