AlgoViz

Single responsibility (SRP)

medium 50 min

A class should have one reason to change: it answers to one group of people.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:20

Single responsibility

1:03Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Spot it: single responsibility

0:34Reel

Theory

Read or listen first. About 3 min.

What it is

The single responsibility principle (SRP) says that a class should have one reason to change. It is the S in SOLID.

A reason to change is not a technical event. It is a person or a group with a wish: accounting wants another rounding, operations want another log format, marketing wants a friendlier mail. Robert C. Martin calls such a group an actor, and their later wording is: a module should be responsible to one, and only one, actor.

So SRP does not mean one method per class, and it does not mean small classes at any price. The other half of the sentence counts as much: gather together what changes for the same reason. A bank account with deposit, withdraw and balance has three methods and one responsibility.

Why it exists

When two groups share a class, a change for one can break the other. The mail text changes on Monday, and on Tuesday the cache is wrong, because both lived in one file and touched the same field.

Testing becomes cheaper. A rule that is mixed with a database and a mail server needs both, or a fake of both, before you can check one line of it.

Teams stop meeting in the same file. And a reader who looks for the mail text finds a class with that name, and does not scroll through two thousand lines.

A short history

  1. 1972

    David Parnas publishes On the Criteria To Be Used in Decomposing Systems into Modules. The advice: give each module a design decision that is likely to change, and hide it there.

  2. 1974

    Wayne Stevens, Glenford Myers and Larry Constantine publish Structured Design, with the terms cohesion (do the parts belong together?) and coupling (how much do modules depend on each other?).

  3. 1996

    Arthur Riel describes the god class in Object-Oriented Design Heuristics: one class that knows or does too much while others are only data.

  4. Late 1990s

    Robert C. Martin joins these ideas into one principle and names it single responsibility. They tell this in a 2014 article.

  5. 2014

    In that article Martin gives a second wording: gather together the things that change for the same reasons, separate those that change for different reasons. And they tie the reasons to people.

  6. 2017

    The book Clean Architecture (Martin) uses the wording with one actor.

Words to know

Responsibility
One reason to change: what one group of people may ask you to change.
Actor
That group. A role, not a person: the same person can be two actors on two days.
Cohesion
How strongly the parts of one class belong together. High is good.
Coupling
How much one class must know about another. Low is good.
God class
A class that knows and does too much. Also called a blob.
Coordinator
A class whose one job is the order of the steps. It calls others and contains none of their rules. Also called an orchestrator.
Accidental sharing
Two things look the same today but belong to different actors, and one method serves both.
Shotgun surgery
The opposite illness: one small wish needs edits in many classes.
LCOM
Lack of cohesion in methods. A family of numbers that show whether the methods of a class use the same fields.
Change coupling
Files that keep changing in the same commits. It is measured in the history, not in the code.
Seam
A place where you can put something else in, for example a fake in a test.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 4

List the actors. Who may ask for a change in this class?

Understand it

Start here

The one-person band

Lee plays three instruments at once. It looks clever, and it works on a sunny day. Watch what happens when one instrument needs care.

Lee, the drum and the flute

Frames 1 to 4 are the god class, 5 to 7 are the principle, 8 is the mistake on the other side.

The smell

A class that does everything

This is how a god class begins. Nobody planned it. Each feature was added where the last one already was.

Python
class UserService:    def __init__(self):        self.rows, self.cache, self.sent, self.lines = {}, {}, [], []    def create_user(self, name, email):        if "@" not in email:                            # 1. rules            raise ValueError("bad email")        self.rows[email] = name                         # 2. database        self.lines.append("INFO created " + email)      # 3. logging        self.send_welcome(email)        return email    def send_welcome(self, email):        body = "Welcome, " + self.find(email)           # 4. mail text        self.sent.append((email, body))                 # 5. mail delivery        self.cache.clear()                              # 6. caching, inside the mail code    def find(self, email):        if email not in self.cache:            self.cache[email] = self.rows[email]        return self.cache[email]s = UserService()s.create_user("Asha", "asha@example.com")print(s.sent)print(s.cache)   # {} : sending a mail emptied the cache for everybody
Before. Find the six reasons to change. One method has a bug that no user wish explains.
Edit and run it in your browser

Who can ask for a change here?

ActorAsks forPart of the class
ProductNames may be empty for guestsRules
Database teamAnother table, another databaseSaving and finding
MarketingA friendlier text, two languagesMail text
Mail providerAnother way to deliverMail delivery
OperationsLogs as JSONLogging
Performance teamCache for 5 minutes onlyCaching
Six rows mean six reasons to change. The number of lines is not in this table, and that is on purpose.

The bad shape: many owners, one class

UserService- rows, cache- smtp, logFile+ createUser()+ updateUser()+ deleteUser()- saveToDb(), queryDb()- sendWelcome(), sendReset()- logAction(), logError()- validateEmail()- getFromCache(), setCache()Product

1/4It starts small

One class, one actor. Product wants to create users.

uses

The boxes around the class are people, not code. This picture is the fastest way to explain SRP on a whiteboard.

The good shape: one owner each

RegisterUser+ run(name, email): User

1/5The order

RegisterUser is the coordinator. It says who comes after whom, and nothing else.

useshas (lives on)

Every box has one owner. Cover any box with your hand: the others still make sense.

Focused classes

  • A test needs one or two stand-ins
  • A change stays in one class
  • Two teams work in two files
  • The name says what it does

God class

  • A test needs a stand-in for everything
  • A change for mail breaks the cache
  • Every team edits the same file
  • The name ends in Manager, because nothing else fits

The key word

What is one responsibility?

A responsibility is not a method, a verb or a number of lines. Three questions find it. They do not always agree, and then the first one wins.

  • Who asks?

    Name the group that may ask for a change. Two groups are two responsibilities, even inside one method.

  • What changes together?

    Look at the last twenty commits. Lines that always change in the same commit belong together.

  • Which fields meet?

    Methods that share no field and do not call each other are strangers under one roof.

  • Can you say it?

    One sentence without the word and. Useful as a first hint. A skilled writer can hide an and.

Same size, different answer

ClassMethodsActorsVerdict
Stackpush, pop, peek, sizeWhoever needs a stackOne responsibility
BankAccountdeposit, withdraw, balanceAccount productOne responsibility
Invoicetotal, save, toPdfAccounting, database, designThree
ShiftpaidHours, used by pay and by planningPayroll, planningTwo, inside one method
RegisterUserrun, which calls four othersProduct (the order of steps)One: coordinating is a job

Do I split this class?

A split costs something too. Two groups and no collision is a reason to prepare, not always a reason to act.

Warning signs

Six signs, and how much they prove

SignExampleStrength
Changes break unrelated featuresA fix in mail breaks the logStrong: it already happened
More than one reason to changeIf the tax law or the mail provider changesStrong
Tests need many stand-insFake database, fake mail, fake logger for one ruleStrong
Many unrelated importsSQL, SMTP, files and HTTP at the topMedium
No good name without And or ManagerUserAndOrderManagerMedium. Some managers manage one thing
Very long classHundreds of linesWeak alone. A parser is long and has one job
Numbers such as 200 or 500 lines are house rules, not laws. Use them to choose where to look, not what to do.

The good signs

SignWhy it matters
The name is a plain nounYou know where to look
Few things are passed inOne or two collaborators, and a test that fits on a screen
All methods use most of the fieldsThe parts belong together
Its commits have one kind of messageOne owner

The hard case

Shared today, different tomorrow

The most expensive violations do not look like a god class. They look like good reuse. Payroll and planning both need the hours of a shift, so both call hours(). Then payroll must round to quarters of an hour.

Python
class Shift:    def __init__(self, start, end): self.start, self.end = start, end     # minutes after midnight    def hours(self):        worked = self.end - self.start        return round(worked / 15) * 15 / 60        # added for payroll: quartersdef pay(shifts, rate): return sum(s.hours() for s in shifts) * ratedef rest_minutes(a, b): return b.start + 24 * 60 - (a.start + int(a.hours() * 60))   # planningmonday, tuesday = Shift(14 * 60, 22 * 60 + 8), Shift(9 * 60, 17 * 60)print(pay([monday], 20))                # 165.0  (8.25 h: right for payroll)print(rest_minutes(monday, tuesday))    # 645, but the real rest is 652
One method, two actors. A correct change for payroll makes planning wrong, and no test of payroll will notice.
Edit and run it in your browser

Payroll is right. Planning now sees 645 minutes of rest. The true value is 652, because the shift really ended at 22:08. If the rule says 650 minutes, planning refuses a legal shift. The two calculations were never the same thing. They only had the same number for a while. The FAANG interview page takes this apart.

The result

Who does what when a user registers

One registration

The coordinator is the only one with several arrows. It has no rule, no SQL and no mail text.

The same three wishes, two designs

What you gain

  • Easier testing

    Small classes need small tests, with one or two stand-ins.

  • Reuse

    A mailer that knows nothing about users can send other mails.

  • Simple care

    A change stays in one class.

  • Clear reading

    The name tells you what is inside.

  • Parallel work

    Two teams, two files, no merge conflict.

  • Fewer surprises

    A bug in one class is rarely felt in another. It can still travel through a wrong return value.

Every level

The same question for functions, classes and services

LevelOne reason to change meansSign that it has two
FunctionOne step at one level of detailA comment such as # now send the mail in the middle
ClassOne actorTwo groups of methods that share no field
PackageClasses that are released togetherYou use one class and pull in a mail library
ServiceOne team, one business abilityTwo teams need a meeting for every deployment
For the service level see microservices. For layers see separation of concerns, which asks the question for a whole program.

Invoice has total(), save() and to_pdf(). What do you do?

BreaksOne class per method
How
InvoiceTotalCalculator, InvoiceLineAdder, InvoiceTaxer and so on.
Limit
Total, lines and tax change together. One new tax rule is now three edits, and Invoice is an empty bag of numbers.
Choose when
Never by method count alone.
WorksKeep it and tidy the file
How
Sections and comments.
Limit
Design and database still meet in one class, and a test of total() imports a PDF library.
Choose when
A script for one person.
StrongKeep the rules, move the neighbours
How
Invoice.total() stays with the lines. InvoiceRepository saves, InvoicePdf draws.
Limit
The neighbours must read the invoice, so it needs good questions to ask it, not only getters.
Choose when
As soon as two actors exist, which here is at once.

Neighbours

How it fits with the other principles

PrincipleTogether with SRP
Open/closedA class with one responsibility can be one extension. A god class can only be edited
Interface segregationSRP looks from inside (who changes me?). ISP looks from outside (what does this caller need?)
Dependency inversionAfter the split the pieces need each other. DIP says through what
EncapsulationSplitting must not turn objects into open bags of data
Anti-patternsThe god class and the anemic model are the two ends of a bad split

Summary

The whole topic in one minute.

Ask of every class: who could ask for a change here? One answer is fine. Two answers are two classes, joined by a thin coordinator that knows only the order.

Split by actor, not by size. A long class with one owner can stay. A short method shared by payroll and planning must go apart.

Splitting moves the difficulty into the joints: transactions, partial failure, order. A good answer names these, and knows when pieces should be merged again.

  • One reason to change means one group of people who may ask.
  • Gather what changes together, separate what does not.
  • Size is a hint. Actors and shared fields are evidence.
  • A coordinator is allowed: its one job is the order.
  • Beware of the method that two actors share by accident.
  • Too many pieces is also a violation: one wish, many edits.

Sources