SRP
SRP — Single Responsibility Principle
"A class should have only one reason to change." — Robert C. Martin, Agile Software Development
"The Single Responsibility Principle is about people. It is the most misunderstood of the SOLID principles." — Uncle Bob, clarification (2014, paraphrased)
Core idea
A class should change only for one reason — it should be answerable to one stakeholder. "One responsibility" means one axis of change, not "one function".
A common misunderstanding
Most people read SRP as "a class should do one thing". That is not accurate. The right reading:
A class should have one reason to change.
The difference matters. A class can have many methods that do many things, and that is fine as long as they all change together, for the same reasons. A class should not combine methods that change for different reasons.
What the difference looks like
class Employee:
def calculate_pay(self): ... # Accounting changes the pay formula
def save_to_db(self): ... # DBA changes the DB schema
def generate_report(self): ... # HR wants a different report format
Three methods, three different stakeholders:
- Accounting
- DBA / DB architect
- HR / management
Any of them can change their requirement independently. One class = one file = potential merge conflicts and side breakage when different teams push changes.
Why it matters
| Without SRP | With SRP |
|---|---|
| Changing the pay formula can touch storage | Each change lives in one small file |
| Testing the formula needs DB mocks, HR-format setup, and so on | The formula test only needs the calculator class |
| Files grow until they are "god classes" (1000+ lines) | Five small files, each easy to read |
| Different teams collide in git | Each team owns its own file |
Reuse is impossible: Employee.save_to_db drags in all of Employee |
Each component stands on its own |
| Understanding the whole class takes real effort | One look is enough |
A classic example: the "god class"
❌ One class, many responsibilities
class Order:
def __init__(self, items: list, customer_email: str):
self.items = items
self.customer_email = customer_email
self.total = 0
def calculate_total(self) -> float:
# Business logic
self.total = sum(i.price * i.qty for i in self.items)
if self.total > 1000:
self.total *= 0.9 # discount
return self.total
def save_to_db(self) -> None:
# Infrastructure
conn = psycopg2.connect("postgresql://...")
cur = conn.cursor()
cur.execute("INSERT INTO orders ...", (self.customer_email, self.total))
conn.commit()
def send_confirmation_email(self) -> None:
# External service
smtplib.SMTP("smtp.gmail.com").sendmail(
"[email protected]", self.customer_email, f"Total: {self.total}"
)
def generate_invoice_pdf(self) -> bytes:
# Presentation / formatting
from reportlab.pdfgen import canvas
...
Four responsibilities in one class:
- Accounting drives
calculate_total(discount formula). - DBA drives
save_to_db(DB schema). - Marketing drives
send_confirmation_email(email text). - Accounting / PDF folks drive
generate_invoice_pdf.
Any change in one "world" touches all the others. Testing the formula needs the DB. Changing the email template means re-testing the PDF.
✅ Split by axes of change
@dataclass(frozen=True)
class Order:
items: list["OrderItem"]
customer_email: str
@dataclass(frozen=True)
class OrderItem:
name: str
price: float
qty: int
# 1. Business logic (formulas, rules)
class OrderCalculator:
DISCOUNT_THRESHOLD = 1000
DISCOUNT_RATE = 0.10
def total(self, order: Order) -> float:
subtotal = sum(i.price * i.qty for i in order.items)
if subtotal > self.DISCOUNT_THRESHOLD:
return subtotal * (1 - self.DISCOUNT_RATE)
return subtotal
# 2. Storage (DB)
class OrderRepository:
def __init__(self, conn): self._conn = conn
def save(self, order: Order, total: float) -> int:
cur = self._conn.cursor()
cur.execute("INSERT INTO orders ...", (order.customer_email, total))
return cur.fetchone()[0]
# 3. Email
class OrderNotifier:
def __init__(self, smtp): self._smtp = smtp
def send_confirmation(self, order: Order, total: float) -> None:
self._smtp.sendmail(
"[email protected]", order.customer_email, f"Total: {total}"
)
# 4. PDF
class InvoiceGenerator:
def to_pdf(self, order: Order, total: float) -> bytes: ...
Now each class has one reason to change and one stakeholder.
Who glues it together?
A thin orchestrator (often called OrderService, OrderUseCase, CheckoutHandler):
class CheckoutService:
def __init__(self, calculator, repo, notifier, invoicer):
self._calculator = calculator
self._repo = repo
self._notifier = notifier
self._invoicer = invoicer
def checkout(self, order: Order) -> bytes:
total = self._calculator.total(order)
self._repo.save(order, total)
self._notifier.send_confirmation(order, total)
return self._invoicer.to_pdf(order, total)
The orchestrator knows the sequence, but does none of the work itself. That is what "glue" means: an orchestration layer.
SRP vs SoC
People mix them up. The difference is the level:
| SoC | SRP | |
|---|---|---|
| Level | Architectural (modules, layers, systems) | Class-level (one class) |
| Question | "What concerns exist here?" | "How many reasons to change does this class have?" |
| Example | I/O / logic / presentation as separate layers | The Order class should not include email logic |
In short: SoC is about the system, SRP is about the class. Both say "do not mix things that change for different reasons", just at different scales.
How to spot a violation of SRP
1. "I, and also…"
If your description goes: "this is Order, and it computes the total, and saves to DB, and sends an email" — that is three responsibilities or more.
2. Imports from different worlds
# In one file or class:
import psycopg2 # DB
import smtplib # email
from reportlab import ... # PDF
import stripe # payments
If a class imports things from different domains, it almost certainly combines responsibilities.
3. Many changes from different people in git history
If git log shows that the file is edited by:
- DBA (schema)
- Marketer (email text)
- Accountant (discounts)
- Lawyer (invoice PDF format)
Four different "nerves" running through one file. Classic SRP violation.
4. "If I change X, what else do I have to update?"
If changing the discount formula also forces edits in storage and email, the responsibilities are tangled. A healthy SRP design: one change, one file.
Common pitfalls
1. The "utility" class
class Utils:
def format_date(self, d): ...
def calculate_tax(self, amount): ...
def send_email(self, to, body): ...
def parse_json(self, s): ...
This is anti-SRP in its purest form. Utils has N responsibilities. Split it by topic: DateFormatter, TaxCalculator, EmailSender, JsonParser. Or just put separate functions into topical modules.
"Utility" is a name with no meaning. It is a bucket for "nowhere else to put this".
2. SRP does not mean "one method"
class StringFormatter:
def to_uppercase(self, s): ...
def to_lowercase(self, s): ...
def trim(self, s): ...
def reverse(self, s): ...
Four methods, but one responsibility (string formatting). This is not an SRP violation. SRP is about reasons to change, not method count.
3. Mixing up "one responsibility" with "one field"
class User:
def __init__(self, name, email, age):
self.name = name
self.email = email
self.age = age
Three fields, one responsibility ("represent a user"). Not a violation.
4. Splitting too finely
class FirstNameValidator: ...
class LastNameValidator: ...
class EmailValidator: ...
class AgeValidator: ...
class UserValidator:
def __init__(self, fn_v, ln_v, e_v, a_v): ...
One class per field validator is over-engineering. Enterprise Java teams often do this. Here "one responsibility" equals "validate a user", and one UserValidator with all the checks is fine.
Rule of thumb: one reason to change is not one line of code. It can be 5 to 15 methods that change together in response to one requirement.
SRP for functions, not just classes
SRP applies to functions too:
❌ A function with several jobs
def process_user(data: dict) -> None:
# 1. Validation
if not data.get("email"): raise ValueError(...)
# 2. Storage
db.insert("users", data)
# 3. Email
smtp.send(data["email"], "Welcome!")
# 4. Analytics
analytics.track("user_signup", data["email"])
✅ Each function does one thing
def validate_user(data: dict) -> None: ...
def save_user(data: dict) -> int: ...
def send_welcome_email(email: str) -> None: ...
def track_signup(email: str) -> None: ...
def process_user(data: dict) -> None: # orchestrator
validate_user(data)
user_id = save_user(data)
send_welcome_email(data["email"])
track_signup(data["email"])
Relationship to other principles
- SoC — same idea, at the layer or module level.
- OCP — only works when SRP is in place: you can add a new
Notifiertype without touchingOrderCalculator. - DIP — the orchestrator depends on abstractions of the components.
- Encapsulation — each class owns its responsibility.
SRP is the foundation that the other four SOLID principles stand on. Without it, SOLID does not work.
Rules of thumb
- "Who will ask for the change?" — if different people, teams, or stakeholders, split.
- "How many reasons to change?" — more than one, time to refactor.
- Do not confuse method count with responsibility count. Ten methods on one topic is normal.
- Do not confuse fields with responsibility. Many fields about one thing is normal.
- Do not over-split. One validator class with 10 checks beats 10 one-method validators.
- "Utility" / "Helper" / "Manager" are suspicious names. They usually mean "I do not know where this belongs".
- If a file grows past 300-400 lines, suspect an SRP violation. It is a signal, not a rule.
- A thin orchestrator that glues things is fine. Its responsibility is orchestration.
One-line summary
One class, one reason to change. One stakeholder whose needs drive the code. If four different teams keep editing the same file, SRP is broken.