Skip to main content

Command Palette

Search for a command to run...

Mastering "S" in S.O.L.I.D 😎.

Updated
2 min read
Mastering "S" in S.O.L.I.D 😎.

A class should have only one reason to change, meaning it should only do one job/responsibility.

💡 Simple Explanation:

If one class handles too many things, any change in one part might accidentally break other parts. That’s risky and messy.

💻 Java Example (❌ Bad - Violates SRP):


public class Employee {
    public void calculateSalary() {
        // Logic to calculate salary
    }

    public void saveToDatabase() {
        // Logic to save employee data
    }

    public void generateReport() {
        // Logic to generate report
    }
}

❌ Here, the Employee class is doing too many things:

  • Salary logic

  • Database logic

  • Report generation

✅ Good Code (Follows SRP):


public class Employee {
    private String name;
    private double salary;

    // Only employee-related properties
}

public class SalaryCalculator {
    public void calculateSalary(Employee employee) {
        // Logic to calculate salary
    }
}

public class EmployeeRepository {
    public void saveToDatabase(Employee employee) {
        // Logic to save employee data
    }
}

public class ReportGenerator {
    public void generateReport(Employee employee) {
        // Logic to generate report
    }
}

✅ Now, each class has one job:

  • Employee → holds employee data

  • SalaryCalculator → calculates salary

  • EmployeeRepository → saves to database

  • ReportGenerator → creates reports

✅ Trick to Check SRP (Hinglish for better understanding):

  1. Class ka naam padhke socho:
    "Kya ye class sirf ek kaam ka representative lag rahi hai?"

  2. Uske methods dekh ke socho:
    "Kya sabhi methods ek hi type ka kaam kar rahe hain?"

👉 Is class ko kab kab change karna padega?

  • Business ne bola calculation logic change karo → calculateTotal()

  • Printing format change hua → printInvoice()

  • Database change hua → saveToDatabase()

➡️ Teen alag-alag reason se change karna pad raha hai. So, SRP break ho gaya.