githubEdit

Single Responsibility

Definition: A class should have one, and only one, reason to change.

The Problem

When a class has multiple responsibilities, changes to one responsibility can affect the others.

❌ 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;
    }
}

Problems:

  • Database schema change → modify Employee class

  • Report format change → modify Employee class

  • Bonus calculation change → modify Employee class

  • Too many reasons to change!


✅ Good Example (Follows SRP)

Benefits:

  • Each class has one reason to change

  • Easy to test (mock database, calculator, etc.)

  • Easy to maintain (change report format without touching data model)

  • Clear responsibilities


Real-World Example: User Authentication

❌ Bad (God Class)


✅ Good (Separated Responsibilities)


How to Identify SRP Violations

Ask yourself:

  1. "What is this class's ONE job?" If you can't answer in one sentence, it's doing too much.

  2. "How many reasons could this class change?" More than one = violation.

  3. "If [X] changes, does this class need to change?" Test for different X (DB schema, UI, business rules)

Example:


Benefits of SRP

Easier to understand: Each class does one thing ✅ Easier to test: Mock dependencies, test single responsibility ✅ Easier to maintain: Change one thing without breaking others ✅ Easier to reuse: Small, focused classes are more reusable ✅ Less coupling: Classes depend on interfaces, not implementations


Common Mistakes

Mistake 1: Too Granular

Rule of Thumb: Class should have 3-10 methods, not 1.

Mistake 2: Anemic Domain Model


Interview Tips

Q: "Explain SRP with an example"

  • A: "A class should have one reason to change. For example, User class shouldn't handle authentication, database operations, and email notifications - split into UserAuthService, UserRepository, NotificationService."

Q: "How do you balance SRP with not having too many classes?"

  • A: "Use common sense. Group related methods into one class if they change together. Don't split every method into a class."

Last updated