Article
Single Responsibility Principle: One Reason to Change
The 'S' in SOLID is about focus. Learn why a module should have only one reason to change.
The Single Responsibility Principle (SRP) is the first of the five SOLID principles of object-oriented design. While often misinterpreted as "a module should do only one thing," the more precise definition given by Robert C. Martin is that a module should have one, and only one, reason to change.
Why One Reason?
In software development, "reason to change" is about stakeholders and requirements. If a class handles both the formatting of a report and the persistence of that report, it has two reasons to change:
- The users want the report format to look different.
- The DBAs want to change the database schema.
When a class has multiple reasons to change, it becomes a magnet for breakage. Changes requested by the formatting requirements might accidentally break the persistence logic, leading to fragile systems.
Identifying Violations
You know you're violating SRP when you find yourself editing a file to change logic that has nothing to do with the feature you're working on. Another symptom is a class that requires imports from many different domains (e.g., UI, Database, and Network).
The Benefits of SRP
- Maintainability: Smaller, focused classes are easier to navigate.
- Testability: It's much simpler to write unit tests for a class that does one specific thing.
- Reusability: A focused component can be reused in different contexts without bringing along unnecessary baggage.
By adhering to SRP, you ensure that your code remains decoupled and resilient to the inevitable shifts in business requirements.
Recommended by our partners
Discussion
Keep the conversation going
Log in to join the discussion.
No comments yet. The first thoughtful reply can set the tone for the whole thread.