A class should always have one responsibility and there should be only a single reason to change it.
Bad Implementation :
Below Employee class contains personal details, business logic to perform a few calculations, and DB logic to save/update.
Our class is tightly coupled, hard to maintain, multiple reasons to modify this class.
publicclassEmployee{privateStringfullName;privateStringdateOfJoining;privateStringannualSalaryPackage;// standard getters and setters methods// business logicpubliclongcalculateEmployeeSalary(Employeeemp){...}publiclongcalculateEmployeeLeaves(Employeeemp){...}publiclongcalculateTaxOnSalary(Employeeemp){...}// data persistence logicpublicEmployeesaveEmployee(Employeeemp){...}publicEmployeeupdateEmployee(Employeeemp)...}}
Good Implementation :
We can split a single Employee class into multiple classes as per their specific responsibility.
It made our class loosely coupled, easy to maintain, and only single reason to modify.
publicclassEmployee{privateStringfullName;privateStringdateOfJoining;privateStringannualSalaryPackage;// standard getters and setters methods}publicclassEmployeeService{// ...publiclongcalculateEmployeeSalary(Employeeemp){...}publiclongcalculateEmployeeLeaves(Employeeemp){...}publiclongcalculateTaxOnSalary(Employeeemp){...}}publicclassEmployeeDAO{// ...publicEmployeesaveEmployee(Employeeemp){...}publicEmployeeupdateEmployee(Employeeemp){...}}