LOW-LEVEL DESIGN · SOLID PRINCIPLES · S · 8 OF 48

Single Responsibility Principle in Java: One Reason to Change

The S in SOLID, explained with a meal-plan billing class that calculates, saves and emails all at once. Learn what "one reason to change" really means, how to split the class into a calculator, a store, a mailer and a small coordinator, how to spot the smell, when not to split, and how it shows up in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 18

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 120 lines, with a small main() demo. Save it as SingleResponsibilityDemo.java, then run javac SingleResponsibilityDemo.java && java SingleResponsibilityDemo.

import java.util.ArrayList;
import java.util.List;

/** Single responsibility: one billing class doing three jobs, then split into focused classes. */
public class SingleResponsibilityDemo {

    public static void main(String[] args) {
        System.out.println("--- Before: one class, three reasons to change ---");
        new MealPlanBilling().billMonth("asha@example.com", 22, 120);

        System.out.println();
        System.out.println("--- After: one job per class ---");
        InMemoryInvoiceStore store = new InMemoryInvoiceStore();
        BillingService billing = new BillingService(new InvoiceCalculator(), store, new ConsoleMailer());
        billing.billMonth("asha@example.com", 22, 120);
        billing.billMonth("ravi@example.com", 30, 120);
        System.out.println("Invoices saved: " + store.count());

        // The pricing rules can be checked alone: no database, no email.
        Invoice check = new InvoiceCalculator().calculate("test", 30, 100);
        System.out.println("Calculator alone, 30 meals at 100: total " + check.total()
                + (check.total() == 2835 ? " (correct)" : " (WRONG)"));
    }
}

// ---------------------------------------------------------------
// BEFORE: pricing, storage and email wording live in one method.
// Finance, the data team and the customer team all edit this class.
// ---------------------------------------------------------------
class MealPlanBilling {

    void billMonth(String email, int meals, long pricePerMeal) {
        // 1. pricing rules (finance decides these)
        long subtotal = meals * pricePerMeal;
        long discount = meals >= 25 ? subtotal / 10 : 0;
        long tax = (subtotal - discount) * 5 / 100;
        long total = subtotal - discount + tax;

        // 2. storage details (the data team decides these)
        String sql = "INSERT INTO invoice(email, meals, total) VALUES ('"
                + email + "', " + meals + ", " + total + ")";
        System.out.println("[db] " + sql);

        // 3. email wording (the customer team decides this)
        System.out.println("[mail] to " + email + ": Dear customer, you owe " + total + " rupees.");
    }
}

// ---------------------------------------------------------------
// AFTER: each class has one reason to change.
// ---------------------------------------------------------------

/** The numbers of one monthly bill. Immutable, so every part can share it safely. */
record Invoice(String customer, int meals, long subtotal, long discount, long tax, long total) { }

/** Pricing rules only. Changes when finance changes the rules. */
class InvoiceCalculator {
    private static final int BULK_MEALS = 25;
    private static final int BULK_DISCOUNT_PERCENT = 10;
    private static final int TAX_PERCENT = 5;

    Invoice calculate(String customer, int meals, long pricePerMeal) {
        long subtotal = meals * pricePerMeal;
        long discount = meals >= BULK_MEALS ? subtotal * BULK_DISCOUNT_PERCENT / 100 : 0;
        long tax = (subtotal - discount) * TAX_PERCENT / 100;
        return new Invoice(customer, meals, subtotal, discount, tax, subtotal - discount + tax);
    }
}

/** Storage only. Changes when the data team changes how invoices are kept. */
interface InvoiceStore {
    void save(Invoice invoice);
}

class InMemoryInvoiceStore implements InvoiceStore {
    private final List<Invoice> rows = new ArrayList<>();

    @Override
    public void save(Invoice invoice) {
        rows.add(invoice);
        System.out.println("[store] saved invoice for " + invoice.customer());
    }

    int count() {
        return rows.size();
    }
}

/** Messaging only. Changes when the customer team rewrites the email. */
interface InvoiceMailer {
    void send(Invoice invoice);
}

class ConsoleMailer implements InvoiceMailer {
    @Override
    public void send(Invoice invoice) {
        System.out.println("[mail] to " + invoice.customer() + ": your bill for " + invoice.meals()
                + " meals is " + invoice.total() + " rupees (discount " + invoice.discount() + ").");
    }
}

/** The workflow only: which steps run, in which order. No rules of its own. */
class BillingService {
    private final InvoiceCalculator calculator;
    private final InvoiceStore store;
    private final InvoiceMailer mailer;

    BillingService(InvoiceCalculator calculator, InvoiceStore store, InvoiceMailer mailer) {
        this.calculator = calculator;
        this.store = store;
        this.mailer = mailer;
    }

    Invoice billMonth(String customer, int meals, long pricePerMeal) {
        Invoice invoice = calculator.calculate(customer, meals, pricePerMeal);
        store.save(invoice);
        mailer.send(invoice);
        return invoice;
    }
}

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?

MealPlanBilling
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.

The principle
  • 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.

What it is NOT
  • 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.

InvoiceCalculator
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.

Two small interfaces
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.

BillingService
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.

Testing the math alone
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.

Smells
  • 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.

Trade-offs
  • 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.

In Java and frameworks
  • 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.

How it relates
  • 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.

Where it comes up
  • 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

Interview questions

What is the single responsibility principle?

A class should have only one reason to change. In practice that means it serves one purpose, or one group of stakeholders, so a change in one area such as pricing does not force edits in a class that also handles storage or messaging.

Does single responsibility mean a class should have only one method?

No. A class can have many methods if they all serve the same purpose. The test is whether the methods change for the same reason, not how many there are. One method per class usually leads to scattered logic.

How do you decide what counts as a "reason to change"?

Ask who would request a change to this code and why. Pricing rules, database schema and email wording are owned by different people and change at different times, so they are different reasons. Code that always changes together belongs together.

How does SRP make code easier to test?

When business rules live in a class without I/O, you test them with plain inputs and outputs, with no database or network setup. Side effects sit behind small interfaces, so tests can pass simple fakes in their place.

Can you over-apply the single responsibility principle?

Yes. Splitting into many tiny classes makes the flow hard to follow and spreads one idea across many files. Split along reasons to change that actually exist today, such as different owners or different rates of change, not every possible future one.

What are the signs that a class violates SRP?

Vague names like Manager or Util, imports from unrelated areas, many people editing the same file for unrelated tickets, tests that need heavy setup, and groups of methods that use completely separate fields are all common signs.

How is SRP related to cohesion?

A class that follows SRP has high cohesion: its fields and methods all work toward one purpose. Low cohesion, where parts of a class barely relate to each other, is usually a sign that it has more than one responsibility.

How would you apply SRP in a parking lot design?

Keep the ParkingLot focused on spots and occupancy, and move fee rules into a FeeCalculator, ticket output into a TicketPrinter and payment into a PaymentProcessor. A small service coordinates entry and exit using these parts.