Skip to content
javahacks.dev
Architecture

Single Responsibility Principle in Java With Real Examples

What the single responsibility principle really means in Java: one reason to change, how to find a class doing too much and how far to split it.

8 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the OpenJDK, Spring Boot and Apache Maven logos.

"A class should do one thing" is the version of the Single Responsibility Principle that most developers learn, and it is the version that produces both useless advice and absurd code. Everything does "one thing" at some level of description: OrderService handles orders. Robert C. Martin's own statement, in his essay on the principle, is sharper: a class should have one reason to change. The reason belongs to a person or a team, such as finance changing how totals are computed, the warehouse changing how stock is reserved or marketing changing the confirmation email. When one class answers to all three, a change for one of them risks breaking the other two. This post uses a realistic class, finds the reasons it changes, splits it with working code, shows the same split in a Spring service, warns about the overcorrection and applies the idea to methods, packages and services. Examples use Java 25 and Spring Boot 4.

The reason to change

Here is a class that is typical of a codebase after two years:

src/main/java/dev/javahacks/orders/OrderService.javajava
@Service
public class OrderService {

    private final JdbcClient jdbc;
    private final JavaMailSender mail;

    public OrderService(JdbcClient jdbc, JavaMailSender mail) {
        this.jdbc = jdbc;
        this.mail = mail;
    }

    public long place(long customerId, List<Line> lines, String country) {
        if (lines.isEmpty()) {
            throw new IllegalArgumentException("an order needs at least one line");
        }
        long subtotal = 0;
        for (Line l : lines) {
            subtotal += l.unitCents() * l.quantity();
        }
        long tax = switch (country) {
            case "DE" -> subtotal * 19 / 100;
            case "FR" -> subtotal * 20 / 100;
            default -> 0;
        };
        long total = subtotal + tax;

        Long id = jdbc.sql("insert into orders (customer_id, total_cents) values (:c, :t) returning id")
                .param("c", customerId).param("t", total).query(Long.class).single();
        for (Line l : lines) {
            jdbc.sql("insert into order_line (order_id, sku, qty) values (:o, :s, :q)")
                    .param("o", id).param("s", l.sku()).param("q", l.quantity()).update();
        }

        var msg = new SimpleMailMessage();
        msg.setTo(emailOf(customerId));
        msg.setSubject("Order " + id);
        msg.setText("Thanks! Your total is " + total / 100.0);
        mail.send(msg);
        return id;
    }
}

It works and it has four jobs: validating input, computing prices and taxes, writing to the database, and composing and sending email. Ask who asks for changes to each:

PieceWho changes itTypical request
ValidationProduct"Limit an order to 50 lines"
Tax and totalsFinance"France changes its rate"
SQLDevelopers or a DBA"Add a column, rename a table"
Email textMarketing"Make the subject friendlier"

Four groups, one file, one class. A pull request from marketing touches the same lines as the tax fix, merges conflict, and the test for the email text needs a database. This is what SRP describes: not a count of methods, but a count of independent forces acting on the file.

Find the violations

Symptoms are easier to spot than principles.

  • The class imports from unrelated layers. JdbcClient and JavaMailSender in one class is a sign of two infrastructure concerns.
  • Describing it needs "and". "It validates the order and computes tax and saves it and sends mail."
  • Changes cluster in unrelated commits. Check the history: git log --oneline -- OrderService.java shows commits about tax, email, SQL and validation, each touching the same file.
  • Tests need elaborate setup. To test the tax rule you must stub a mail sender and a database.
  • The class is the merge conflict hot spot every sprint.
  • Fields that only some methods use. Half the fields are used by half the methods.

Run the history check; it is objective evidence rather than taste:

Shell
git log --since=1.year --format=%s -- src/main/java/dev/javahacks/orders/OrderService.java | head -8
Text
Fix French VAT rate
Add order line limit
Rename order_line column
Change confirmation email wording
Handle empty basket
Round tax half-even

Six commits, four unrelated reasons. That is the case for splitting.

Refactor

Extract each responsibility to a class named for what it does, with the smallest interface that serves its caller. The pure logic, tax and totals, becomes a class with no dependencies, which is the easiest thing to test:

src/main/java/dev/javahacks/orders/PriceCalculator.javajava
public class PriceCalculator {

    public record Quote(long subtotalCents, long taxCents) {
        public long totalCents() { return subtotalCents + taxCents; }
    }

    public Quote quote(List<Line> lines, String country) {
        long subtotal = lines.stream().mapToLong(l -> l.unitCents() * l.quantity()).sum();
        long tax = switch (country) {
            case "DE" -> subtotal * 19 / 100;
            case "FR" -> subtotal * 20 / 100;
            default -> 0;
        };
        return new Quote(subtotal, tax);
    }
}
src/test/java/dev/javahacks/orders/PriceCalculatorTest.javajava
class PriceCalculatorTest {

    @Test
    void frenchOrdersCarryTwentyPercent() {
        var quote = new PriceCalculator().quote(List.of(new Line("A-100", 2, 5_000)), "FR");

        assertThat(quote.subtotalCents()).isEqualTo(10_000);
        assertThat(quote.taxCents()).isEqualTo(2_000);
        assertThat(quote.totalCents()).isEqualTo(12_000);
    }
}
Text
PriceCalculatorTest > frenchOrdersCarryTwentyPercent() PASSED

The finance rule now has a test that runs in a millisecond with no mail server or database. Persistence and notification each get their own class:

src/main/java/dev/javahacks/orders/OrderRepository.javajava
@Repository
class OrderRepository {

    private final JdbcClient jdbc;

    OrderRepository(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    long save(long customerId, long totalCents, List<Line> lines) {
        Long id = jdbc.sql("insert into orders (customer_id, total_cents) values (:c, :t) returning id")
                .param("c", customerId).param("t", totalCents).query(Long.class).single();
        for (Line l : lines) {
            jdbc.sql("insert into order_line (order_id, sku, qty) values (:o, :s, :q)")
                    .param("o", id).param("s", l.sku()).param("q", l.quantity()).update();
        }
        return id;
    }
}
src/main/java/dev/javahacks/orders/OrderConfirmation.javajava
@Component
class OrderConfirmation {

    private final JavaMailSender mail;

    OrderConfirmation(JavaMailSender mail) {
        this.mail = mail;
    }

    void send(String to, long orderId, long totalCents) {
        var msg = new SimpleMailMessage();
        msg.setTo(to);
        msg.setSubject("Order " + orderId);
        msg.setText("Thanks! Your total is " + totalCents / 100.0);
        mail.send(msg);
    }
}

In a service class

What remains of OrderService is the one responsibility that was always its own: coordinating the steps of the use case and owning the transaction boundary.

src/main/java/dev/javahacks/orders/OrderService.javajava
@Service
public class OrderService {

    private final PriceCalculator prices;
    private final OrderRepository orders;
    private final OrderConfirmation confirmation;
    private final CustomerDirectory customers;

    OrderService(PriceCalculator prices, OrderRepository orders,
                 OrderConfirmation confirmation, CustomerDirectory customers) {
        this.prices = prices;
        this.orders = orders;
        this.confirmation = confirmation;
        this.customers = customers;
    }

    @Transactional
    public long place(long customerId, List<Line> lines, String country) {
        if (lines.isEmpty()) {
            throw new IllegalArgumentException("an order needs at least one line");
        }
        var quote = prices.quote(lines, country);
        long id = orders.save(customerId, quote.totalCents(), lines);
        confirmation.send(customers.emailOf(customerId), id, quote.totalCents());
        return id;
    }
}

The service reads like the use case: check, price, save, confirm. It changes when the workflow changes, not when a tax rate or an email subject does. Each of the four reasons now has its own file, its own tests and its own conflicts. One caution: sending the email inside the transaction means a rollback after the send leaves the customer with a confirmation for an order that does not exist; in a real system, publish an event after commit and send the mail from a listener. The coordination of services into modular boundaries is the subject of Spring Modulith.

Do not overdo it

SRP applied without judgment produces a different mess: a class for every method, OrderValidator, OrderValidatorImpl, OrderValidatorFactory, and a reader who must open eleven files to follow one request. Signs that you split too far:

  • A class with one method that is called from exactly one place and will never have a second caller or a second implementation.
  • Names ending in Helper, Manager or Processor with no clear job.
  • Every change touching five files that always change together. Things that change together for the same reason belong together; that is the other half of the principle.
  • Tests that mock every neighbor and verify the order of calls, which restate the implementation.

The check is the same as before, in reverse: look at the history. If two classes always appear in the same commits, they have one reason to change and should be one class. Do not split a class because it is long; split it because two independent groups of people change it. A 300-line class with one reason to change is fine, and a 60-line class with three is not. The related set of rules and where each one gives way is in SOLID principles with realistic Java examples, and the neighboring advice about function size and naming is in clean code in Java and which rules hold up.

Responsibility at other levels

The same question works at every scale.

Methods. A method that parses, validates and saves has three reasons to change. Extract the steps until each method has one level of abstraction.

Packages. A package util or common collects unrelated things because they were unwelcome elsewhere. Package by feature (orders, billing, catalog) so changes for one business area stay in one place.

Services. A microservice that owns orders, customers and invoicing changes for three reasons. Domain-driven design's bounded contexts are SRP at the scale of a system, discussed in service boundaries with DDD.

Configuration and build. A pom.xml that declares plugins for code generation, packaging and release is one file with several owners; split into a parent and modules when the owners differ.

The Java language gives you the vocabulary for all of this: classes, packages and modules are the units to draw responsibility boundaries around, as the Oracle tutorials on classes and objects lay out.

Where the principle gives way

A small script, a prototype or a data-transfer record has one purpose and needs no decomposition. Performance-critical code sometimes keeps related steps together to avoid allocation and indirection, and a measured reason beats the principle. A class whose responsibilities genuinely change together, as in a tightly coupled parser and its tokenizer, is better left as one unit. And when a team is of two people and changes reach every part, the cost of the extra files exceeds the benefit of the separation. Use the principle as a question to ask when a class hurts, not as a rule to apply when it does not.

Also inJava Core
Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.