Single Responsibility Principle
A class should have one main responsibility, one reason to change. When unrelated jobs live in the same class, a change to one job risks breaking the others.
class EmployeeManager {
double calculateSalary(Employee e) {
// salary logic
return 0;
}
void sendEmail(Employee e, String msg) {
// email logic
}
void printReport(List<Employee> list) {
// report logic
}
void saveToDatabase(Employee e) {
// database logic
}
}class SalaryCalculator {
double calculate(Employee e) {
return 0;
}
}
class EmailService {
void send(Employee e, String msg) {
}
}
class ReportGenerator {
void print(List<Employee> list) {
}
}
class EmployeeRepository {
void save(Employee e) {
}
}Diagram loads as you scroll.
Diagram loads as you scroll.
Now changing how salary is calculated cannot accidentally break email sending or report printing, because each concern lives in its own class.