Single Responsibility Principle
A class should have one reason to change
Overview
The Single Responsibility Principle (SRP) states that a class should have only one reason to change. In other words, a class should have only one job or responsibility.
This principle helps in creating maintainable, testable, and flexible code. When a class has multiple responsibilities, changes to one responsibility might affect the others, making the code fragile.
Key Concepts
One class = One responsibility
A class should have only one reason to change
High cohesion within a class
Easier testing and maintenance
Better code organization
Code Example
1// ❌ BAD: Multiple responsibilities
2class Employee {
3 private String name;
4 private double salary;
5
6 public void calculateSalary() {
7 // Calculate salary logic
8 }
9
10 public void saveToDatabase() {
11 // Database save logic
12 }
13
14 public void generateReport() {
15 // Report generation logic
16 }
17}
18
19// ✅ GOOD: Single responsibility per class
20class Employee {
21 private String name;
22 private double salary;
23
24 public double calculateSalary() {
25 // Only handles salary calculation
26 return salary * 1.1; // 10% bonus
27 }
28
29 // Getters and setters
30}
31
32class EmployeeRepository {
33 public void save(Employee employee) {
34 // Only handles database operations
35 System.out.println("Saving employee to database...");
36 }
37
38 public Employee findById(String id) {
39 // Retrieval logic
40 return null;
41 }
42}
43
44class EmployeeReportGenerator {
45 public void generateReport(Employee employee) {
46 // Only handles report generation
47 System.out.println("Generating report for: " + employee.getName());
48 }
49}The bad example has Employee doing too much. The good example separates concerns into three classes, each with one responsibility.
When to Use
When designing new classes
When refactoring large, complex classes
When a class is changing frequently
When multiple developers work on the same codebase
Advantages
- ✓
Easier to understand and maintain
- ✓
Better testability - each class is focused
- ✓
Lower coupling between classes
- ✓
Easier to extend without breaking existing code
- ✓
Team members can work on different responsibilities in parallel
Disadvantages
- ✗
May lead to more classes in the system
- ✗
Can be over-applied, creating too many small classes
- ✗
Requires good judgment to identify responsibilities
Real-World Example
In a restaurant:
- Chef (cooks food) ≠ Waiter (serves customers) ≠ Cashier (handles payment) Each person has one clear responsibility.
In software:
- UserService (business logic) ≠ UserRepository (data access) ≠ UserController (handles HTTP requests)
Best Practices
- 1.
Ask: "What is the ONE thing this class does?"
- 2.
If class name has "And" or "Manager", it might be doing too much
- 3.
Keep classes small (under 200-300 lines)
- 4.
Use meaningful names that reflect the single responsibility
- 5.
Refactor when you need to change a class for multiple reasons
💡 Interview Tips
Start with the definition: one reason to change
Give a clear before/after example
Mention it improves testability and maintainability
Discuss how it reduces coupling
Be ready to identify SRP violations in code