Single Responsibility
The Problem
❌ Bad Example (Violates SRP)
public class Employee {
private String name;
private double salary;
// Responsibility 1: Employee data management
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
this.salary = salary;
}
// Responsibility 2: Salary calculation (business logic)
public double calculateBonus() {
return salary * 0.1;
}
// Responsibility 3: Database operations
public void save() {
Database.execute("INSERT INTO employees VALUES (?, ?)", name, salary);
}
// Responsibility 4: Report generation
public String generateReport() {
return "Employee: " + name + ", Salary: $" + salary;
}
}✅ Good Example (Follows SRP)
Real-World Example: User Authentication
❌ Bad (God Class)
✅ Good (Separated Responsibilities)
How to Identify SRP Violations
Benefits of SRP
Common Mistakes
Mistake 1: Too Granular
Mistake 2: Anemic Domain Model
Interview Tips
Last updated