Single Responsibility Principle
A class should have one reason to change, and a reason to change is a group of people who ask for changes.
Overview
The Single Responsibility Principle (SRP) is the S in SOLID. Robert C. Martin stated it as: a class should have one, and only one, reason to change. The word responsibility confuses people, because it sounds like one job or one method. Martin's own clarification is that a reason to change is a person, or a group of people, who ask for changes. A class that serves two groups will be changed by both, and each change risks breaking the other group's feature.
The idea is older than the name. David Parnas wrote in 1972 that a module should hide one design decision that is likely to change. Larry Constantine's cohesion, and the work of Tom DeMarco and Meilir Page-Jones, said the same thing in the language of structured design. SRP is that idea applied to classes.
Reasons to change are people
Martin's example is an Employee class with three methods. Each one is asked for by a different part of the business, and keeping all three together hurts in a different way for each.
- calculate_pay(): finance asks for changes. Because it shares a class with the others, a payroll rule change is deployed with unrelated code.
- report_hours(): operations asks for changes. A report tweak can break pay when the two methods share a helper.
- save(): the database team asks for changes. A schema change forces a retest of payroll and reports.
So three groups, finance, operations and the database team, all pull on one Employee class that does pay, reporting and saving. Every change from any of the three groups lands in the same file and can break the other two.
The fix gives each group its own class.
Interview questions
- How do you identify SRP violations?
- How do you apply SRP without an explosion of tiny classes?
- What is the difference between cohesion and SRP?
- Does SRP apply to functions, modules and services, or only classes?
- Refactor this class that violates SRP.
Sign up free to read the full topic
More Low-Level Design topics
Start free on Cariara · Coding problems · System design studio