CodesJava

Easy learning with example program codes

Single Responsibility Principle Java


The object oriented design principles are used to achieve highly cohesive and loosely couple solution. Design principles provides us a way to create the clean and modular design.

The SOLID principles of Object Oriented Design include following five principles:

  • Single Responsibility Principle (SRP)
  • Open Closed Design Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Injection or Inversion principle (DIP)

Single Responsibility Principle (SRP)

It is a SOLID design principle and represent “S” on the SOLID acronym. According to SRP a class should always handle single functionality or there should not be more than one reason for a class to change. It is used to achieve loose coupling between two different functionalities.

Let us understand the single responsibility principle by below example. In the below we have an Employee class which consists of its properties and a method which returns whether the promotion is due for that Employee or not.

public class Employee{
  private String empId;
  private String name;
  private string address; 
 
  public boolean isPromotionDueThisYear(){
    //promotion logic
  }
 
  //Getters & Setters
}

The above class is not following single responsibility principle because Employee class should have the single responsibility of maintaining core attributes of an employee. Calculating whether the promotion is due for that Employee or not is not the responsibility of Employee class.

Better Solution:
We can create a new class which will contain the promotion calculation logic separately. This approach will follow the single responsibility principle because now both classes Employee and Promotions have single responsibilities.

public class Promotions{
  public boolean isPromotionDueThisYear(Employee emp){
    //promotion logic
  }
}
 
public class Employee{
  private String empId;
  private String name;
  private string address;   
 
  //Getters & Setters
}

 



Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap