SRP
Why should a class only have one reason to change? Master the Single Responsibility Principle to build focused and maintainable modules.
The Single Responsibility Principle (SRP) is the "S" in SOLID. It is the most fundamental rule of clean code. It states that a class should have one, and only one, reason to change.
The Essentials
The "One Job" guide:
- Focus: A class should do one thing and do it well.
- Cohesion: High cohesion means all the code inside a class is closely related to its single purpose.
- Easier Testing: When a class only does one thing, it is much easier to write unit tests for it.
- Reduced Side-Effects: Changing a class for its primary reason shouldn't accidentally break unrelated features.
The Swiss Army Knife Problem
Imagine a tool that is a hammer, a screwdriver, a saw, and a spoon all at once.
- It's heavy: You carry the weight of the saw even when you just want to eat soup.
- It's fragile: If the saw blade breaks, you might have to throw away the whole tool, including the spoon.
Software "God Classes" are like this. If your User class handles database saving, email sending, and password validation, it has too many reasons to change. If you change the email provider, you risk breaking the database logic.
SRP in Action
Imagine we have a Student class. Should it handle their name/age AND their teacher assignments?
The class handles data, teachers, and extracurriculars. It has too many reasons to change.
name: string;
assignTeacher(t: Teacher);
enrollInSports(s: Sport);
}
If the sports logic changes, you have to modify the Student file. This is risky.
We split responsibilities into separate services. The Student class stays lean.
class TeacherService { assign(s, t); }
class SportsService { enroll(s, t); }
Each class does one thing well. Testing is easier and side-effects are reduced.
The Manager Test: "And"
A simple way to check if your class violates SRP is to describe it to your manager. If you use the word "and", you probably have a violation.
- "This class handles user login and saves logs to a file." -> Violation!
- "This class calculates the tax for an order." -> Clean!
By following SRP, you ensure that your code is modular, easy to understand, and safe to change.
Next, we'll learn about the Open-Closed Principle and how to avoid the "Inheritance Trap."
Practice what you just read.