Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 57 ยท Design Principles

Single Responsibility Principle

Learn the Single Responsibility Principle: reasons to change, cohesion, how to split a god class, and a before and after report printer example you can run.

The Single Responsibility Principle (SRP) is the first letter of SOLID, and it is the most quoted and the most misunderstood. The usual slogan is "a class should do one thing". That slogan is too vague to apply. A sharper version, from Robert C. Martin, is: a module should have one, and only one, reason to change. More precisely, it should answer to one actor, one group of people who would ask for changes.

Why does this matter? Because code that mixes concerns turns every change into a risk. If the same class formats a report and calculates the numbers in it, a request to change the layout can accidentally break the arithmetic. Separating reasons to change keeps edits local, makes tests smaller, and lets different people work in parallel without collisions.

One reason to change

Finance asks Change how totals are calculated.
Design asks Change how the report looks.
Ops asks Change where reports are stored.

Three requesters, three reasons. Three classes.

1 / 2

Reasons to change

Imagine a class Report that does three things: computes totals, renders text, and saves a file. Three different groups depend on it. The finance team cares about the totals. The design team cares about the layout. The operations team cares about where files go. When finance changes a rule, the layout code sits in the same file, and the same deploy ships all three. A bug in one change can break another team's feature.

Notice the principle is about people and change, not about size. A class with 300 lines that serves one actor can respect SRP. A class with 30 lines that serves three can violate it.

Cohesion: the positive side

The reverse view is cohesion: the degree to which the parts of a class belong together. A cohesive class uses most of its fields in most of its methods. A low-cohesion class has islands: some methods touch fields A and B, others touch only C and D. Those islands are a hint that two classes are hiding inside one.

A quick test: describe the class in one sentence without using "and" or "or". "It calculates sales totals" passes. "It calculates totals and formats them and saves them" fails.

A god class you can run

Here is a typical offender, the god class: it knows everything and everyone depends on it.

JS Before: one class, three reasons to change

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Suppose finance now wants tax added to the total, design wants an HTML version, and ops wants to store reports in cloud storage. All three edit this one class. The save method is also tied to render, so you cannot save an HTML report without changing the class.

After: one class per reason

Split by reason to change. The data and rules stay in one place, and presentation and storage become separate collaborators.

JS After: calculation, rendering and storage separated

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now each change has one home. Tax rules go in SalesData. A new format is a new renderer class. A new storage backend is a new store with a write method. The same refactor in Java would use an interface for the renderer and store:

Java
interface ReportRenderer { String render(SalesData data); }

class TextRenderer implements ReportRenderer {
    public String render(SalesData data) { /* build text */ return ""; }
}

class ReportService {
    private final ReportRenderer renderer;
    private final FileStore store;

    ReportService(ReportRenderer renderer, FileStore store) {
        this.renderer = renderer;
        this.store = store;
    }

    void publish(String name, SalesData data) {
        store.write(name, renderer.render(data));
    }
}

Where to draw the line

SRP can be over-applied. If you split every method into its own class you get dozens of tiny classes that always change together, which is worse than the god class. Use these guides:

  1. Split by actor or axis of change, not by verb. If two things always change together for the same reason, keep them together.
  2. Wait for evidence. If a class has only ever had one kind of change request, do not pre-split it. When a second kind of change arrives, split then.
  3. Watch for the shotgun surgery smell. If one change forces edits in six tiny classes, you split too far or along the wrong axis.
  4. Apply it at several levels. SRP also applies to functions (a function that validates, saves and emails does three things) and to modules or services.

SRP is also the principle behind many patterns. Strategy pulls a varying rule out of its caller. Facade gives a coordinating class the single job of orchestrating, while workers do the real work. Repository isolates persistence.

A function-level check

The principle works at the smallest scale too. Run this and see how a function that does three things becomes three one-line steps.

JS SRP for functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both versions give the same results, but only the second lets you change validation without touching formatting.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the best summary of the Single Responsibility Principle?

    SRP is about reasons to change. Size and method count are not the point.
  2. 2. A class has fields A and B used by half its methods, and fields C and D used by the other half. What does this suggest?

    Methods that use disjoint fields mean the class has islands, a classic sign of low cohesion and mixed responsibilities.
  3. 3. After splitting the report class, finance changes the tax rule. Which class should change?

    Business rules such as totals and tax live in SalesData. Renderers and stores are unaffected.
  4. 4. Which is a sign you split a class too far?

    When one change touches many tiny classes (shotgun surgery), the pieces change together and probably belong together.

Summary

  • SRP: a module should have one reason to change, serving one actor.
  • Cohesion is the positive view: the members of a class belong together.
  • A god class mixes business rules, presentation and storage; split by reason to change.
  • Do not split by verbs or pre-split without evidence; things that change together stay together.
  • SRP applies to functions, classes and services, and underlies patterns such as Strategy, Facade and Repository.

Next, the principle that makes those split-out pieces easy to extend: Open/Closed Principle.