Notes
The problem
Here is a meal plan service. At the end of each month, one method called bill month does everything. It multiplies meals by price, gives ten percent off for twenty five meals or more, adds five percent tax, writes a row to the database and sends an email. It works, and it is only a few lines long. So what is wrong with it?
void billMonth(String email, int meals,
long pricePerMeal) {
long sub = meals * pricePerMeal;
if (meals >= 25) sub -= sub / 10;
long tax = sub * 5 / 100;
db.execute("INSERT INTO invoice ...");
smtp.send(email, "Dear customer, you
owe " + (sub + tax) + " rupees");
} Three reasons to change
Ask who will want this code to change. The finance team changes discount and tax rules. The data team moves invoices to a new database. The customer team rewrites the email text. Three groups, three kinds of decision, one file. Every change risks breaking the other two jobs, they cause merge conflicts, and you cannot test the price math without a database and a mail server.
The idea
The principle says a class should have only one reason to change. A reason to change is not a method or a line of code. It is a kind of decision, usually owned by one group of people. Pricing is one decision. Storage is another. Email wording is a third. Put things that change together in the same class, and keep apart the things that change for different reasons.
- a class should have only one
- reason to change
- reason to change =
- one kind of decision, owned
- by one group of people
- keep together what changes
- together; keep apart what
- changes for different reasons
A common misreading
A common mistake is to read this as one method per class. That is not the idea. A calculator can have five methods and still have one responsibility, because they all serve the same purpose. A quick test: describe the class in one sentence. If you need the word and, as in it prices and saves and emails, it probably has more than one reason to change.
- not: one method per class
- not: one line of work
- not: split until it hurts
- it IS:
- one purpose you can name
- without the word "and"
- InvoiceCalculator: prices
- MealPlanBilling: prices AND
- saves AND emails
The split
Here is the split. An invoice calculator owns the pricing rules and returns an invoice record. An invoice store saves invoices. An invoice mailer sends them. A thin billing service coordinates the steps in order but contains no rules of its own. Each class now has exactly one reason to change, and the coordinator only changes if the steps themselves change.
Pricing in one place
The calculator holds all the pricing rules and nothing else. Numbers go in, and an immutable invoice record comes out, with the subtotal, the discount, the tax and the total. It does not know that databases or emails exist. When finance changes the discount from ten to fifteen percent, this is the only file that changes.
Invoice calculate(String customer,
int meals, long price) {
long sub = meals * price;
long off = meals >= 25 ? sub / 10 : 0;
long tax = (sub - off) * 5 / 100;
return new Invoice(customer, meals,
sub, off, tax, sub - off + tax);
}
no database, no email, no I/O Saving and sending
Saving and sending each get their own small interface. The invoice store has one method, save. The invoice mailer has one method, send. The real versions talk to a database and a mail server. In the demo, an in memory store and a console mailer stand in for them. The data team only touches the store, and the customer team only touches the mailer and its email template.
interface InvoiceStore {
void save(Invoice invoice);
}
interface InvoiceMailer {
void send(Invoice invoice);
}
SqlInvoiceStore, InMemoryInvoiceStore
SmtpInvoiceMailer, ConsoleMailer The coordinator
The billing service is now short and boring, which is good. It asks the calculator for an invoice, hands it to the store, then to the mailer, and returns it. Its one job is the workflow: which steps happen and in what order. If the business later says send the email before saving, or skip the email for corporate clients, this is the class that changes.
Invoice billMonth(String customer,
int meals, long price) {
Invoice inv =
calculator.calculate(customer,
meals, price);
store.save(inv);
mailer.send(inv);
return inv;
} Run-through
Follow one bill. The service asks the calculator for twenty two meals at one hundred and twenty rupees each. The calculator builds an invoice record. The service passes it to the store, which saves it, and then to the mailer, which sends it. Each class did one thing, and the invoice record is the single piece of data they all share.
Who changes what
Now look at the teams again. Finance edits only the calculator. The data team edits only the store. The customer team edits only the mailer. Their changes no longer land in the same file, so one team cannot accidentally break another, code reviews are smaller, and merge conflicts mostly disappear. That is the real payoff of the principle.
Easy to test
Testing becomes easy. To check the discount rule you build a calculator and pass plain numbers. Thirty meals at one hundred rupees is three thousand, minus three hundred discount, plus one hundred thirty five tax, gives two thousand eight hundred thirty five. No database, no mail server, no setup. Before the split, that same test needed a database connection and an email stub.
Invoice inv = new InvoiceCalculator()
.calculate("test", 30, 100);
// 3000 - 300 off + 135 tax
assert inv.total() == 2835;
no database to start
no fake mail server
runs in milliseconds How to spot it
How do you spot a class that breaks this principle? Vague names like manager or helper are a hint. So are imports from unrelated worlds, such as SQL, HTTP and PDF in one file. Tests that need a lot of setup, many people editing the file for unrelated tickets, and groups of methods that use completely separate fields all suggest the class is really two or three classes glued together.
- name ends in Manager, Helper,
- Util, or contains And
- imports from unrelated areas:
- SQL + HTTP + PDF + pricing
- tests need a lot of setup
- many people edit it for
- unrelated tickets
- some methods use fields that
- other methods never touch
- hundreds of lines that grow
Do not over-split
Like every principle, this one can be overdone. Splitting a fifty line class into ten tiny classes makes the flow hard to follow. Split along reasons to change that really exist: different owners, different speeds of change, or parts you need to test or replace on their own. If a class is small and has only one real reason to change today, leave it alone.
- too many tiny classes:
- hard to follow the flow
- logic scattered everywhere
- split when:
- different people change it
- parts change at different
- speeds or for different
- reasons
- wait when: it is small and
- only one reason exists today
Where you see it
You already see this idea in Java. A local date holds a date, but turning it into text belongs to the date time formatter. Even the format method on local date just hands the work to the formatter you pass in. In Spring applications, the usual layers follow the same thinking: controllers handle HTTP, services hold business rules, and repositories handle storage.
- LocalDate: holds a date
- DateTimeFormatter: turns it
- into text; LocalDate.format
- just delegates to it
- Spring layers by convention:
- controller: HTTP
- service: business rules
- repository: storage
Related ideas
This principle is closely linked to high cohesion, where everything in a class serves the same purpose. Separation of concerns is the same idea at the level of layers and services. Interface segregation, coming up in this unit, applies it to interfaces. And our billing service acts like a small facade, one simple entry point over several focused parts.
- high cohesion: everything in
- the class serves one purpose
- separation of concerns: the
- same idea at system level
- interface segregation: the
- same idea for interfaces
- BillingService is a small
- facade over the three parts
In LLD interviews
In LLD interviews this shows up everywhere. In a parking lot, fee rules belong in a fee calculator, not inside the parking lot class. In a vending machine, inventory and payment are separate. In an expense splitting app, the balance sheet and the settlement suggestions are separate. The two classic mistakes are one giant manager class, and the opposite, a separate class for every single method.
- parking lot: FeeCalculator,
- not fees inside ParkingLot
- vending machine: Inventory
- apart from PaymentHandler
- splitwise: BalanceSheet apart
- from SettlementSuggester
- mistake: one Manager class
- that does everything
- mistake: a class per method