Single responsibility (SRP)
medium 50 minA class should have one reason to change: it answers to one group of people.
Video lesson · Chapter 1 of 6
Make a prediction
Single responsibility
1:03Reel
More reels
One idea each, a minute or less.
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
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.
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?).
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.
Late 1990s
Robert C. Martin joins these ideas into one principle and names it single responsibility. They tell this in a 2014 article.
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.
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.
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.
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.
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 everybodyWho can ask for a change here?
| Actor | Asks for | Part of the class |
|---|---|---|
| Product | Names may be empty for guests | Rules |
| Database team | Another table, another database | Saving and finding |
| Marketing | A friendlier text, two languages | Mail text |
| Mail provider | Another way to deliver | Mail delivery |
| Operations | Logs as JSON | Logging |
| Performance team | Cache for 5 minutes only | Caching |
The bad shape: many owners, one class
1/4It starts small
One class, one actor. Product wants to create users.
uses
The good shape: one owner each
1/5The order
RegisterUser is the coordinator. It says who comes after whom, and nothing else.
useshas (lives on)
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
| Class | Methods | Actors | Verdict |
|---|---|---|---|
Stack | push, pop, peek, size | Whoever needs a stack | One responsibility |
BankAccount | deposit, withdraw, balance | Account product | One responsibility |
Invoice | total, save, toPdf | Accounting, database, design | Three |
Shift | paidHours, used by pay and by planning | Payroll, planning | Two, inside one method |
RegisterUser | run, which calls four others | Product (the order of steps) | One: coordinating is a job |
Do I split this class?
Warning signs
Six signs, and how much they prove
| Sign | Example | Strength |
|---|---|---|
| Changes break unrelated features | A fix in mail breaks the log | Strong: it already happened |
| More than one reason to change | If the tax law or the mail provider changes | Strong |
| Tests need many stand-ins | Fake database, fake mail, fake logger for one rule | Strong |
| Many unrelated imports | SQL, SMTP, files and HTTP at the top | Medium |
| No good name without And or Manager | UserAndOrderManager | Medium. Some managers manage one thing |
| Very long class | Hundreds of lines | Weak alone. A parser is long and has one job |
The good signs
| Sign | Why it matters |
|---|---|
| The name is a plain noun | You know where to look |
| Few things are passed in | One or two collaborators, and a test that fits on a screen |
| All methods use most of the fields | The parts belong together |
| Its commits have one kind of message | One 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.
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 652Payroll 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 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
| Level | One reason to change means | Sign that it has two |
|---|---|---|
| Function | One step at one level of detail | A comment such as # now send the mail in the middle |
| Class | One actor | Two groups of methods that share no field |
| Package | Classes that are released together | You use one class and pull in a mail library |
| Service | One team, one business ability | Two teams need a meeting for every deployment |
Invoice has total(), save() and to_pdf(). What do you do?
BreaksOne class per method
- How
InvoiceTotalCalculator,InvoiceLineAdder,InvoiceTaxerand so on.- Limit
- Total, lines and tax change together. One new tax rule is now three edits, and
Invoiceis 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.InvoiceRepositorysaves,InvoicePdfdraws.- 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
| Principle | Together with SRP |
|---|---|
| Open/closed | A class with one responsibility can be one extension. A god class can only be edited |
| Interface segregation | SRP looks from inside (who changes me?). ISP looks from outside (what does this caller need?) |
| Dependency inversion | After the split the pieces need each other. DIP says through what |
| Encapsulation | Splitting must not turn objects into open bags of data |
| Anti-patterns | The 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
- Robert C. Martin: The Single Responsibility Principle (2014)
- Single-responsibility principle, wording with actors
- Cohesion in computer science
- God object
- Martin Fowler: Anemic Domain Model
- Martin Fowler: Strangler Fig
- Martin Fowler: Active Record
- Transactional outbox
- Postfix architecture overview
- Kubernetes: controllers
- Docker: building best practices
- React: Thinking in React
- Python: logging
- Spring MVC: special bean types
- Pro Git: plumbing and porcelain
- PMD: GodClass rule