This is the principle that simply described through cohesion.

Facts :

Each responsibility should be a separate class.

Because each responsibility is an axis of change.

So simply, there should never be more than one reason for a class to change.

Example :

Bad SRP Design

WeatherDisplay.java

public class WeatherDisplay{

 private int temperature;
 private int windSpeed;

public WeatherDisplay(int temperature, int windSpeed){
 this.temperature = temperature;
 this.windSpeed = windSpeed;
 }

public void DisplayWeather(){
 DisplayTemperature();
 DisplayWindSpeed();
 }

private void DisplayTemperature(){
 System.out.println("The current temperature is: " + temperature + " degrees celcius.");
 }

 private void DisplayWindSpeed(){
 System.out.println("The current wind speed is: " + windSpeed + " meters per second.");
 }
}

Here, WeatherDisplay class has two distinct responsibilities (display Temperature and display Wind Speed). So,  There’s two reason to change the WeatherDisplay class in the future. (Eg :  the temperature should be displayed in Fahrenheit and the wind speed should be displayed in knots)

Good SRP Desing

WeatherDisplay.java

public class WeatherDisplay{

 private DisplayTemperature displayTemperature;
 private DisplayWindSpeed displayWindSpeed;

public WeatherDisplay(int temperature, int windSpeed){
 displayTemperature = new DisplayTemperature(temperature);
 displayWindSpeed = new DisplayWindSpeed(windSpeed);
 }

public void DisplayWeather(){
 displayTemperature.Display();
 displayWindSpeed.Display();
 }
}

DisplayTemperature.java


public class DisplayTemperature{
 private int temperature;

public DisplayTemperature(int temperature){
 this.temperature = temperature;
 }

public void Display(){
 System.out.println("The current temperature is: " + temperature + " degrees celcius.");
 }
}

DisplayWindSpeed.java


public class DisplayWindSpeed{
 private int windSpeed;

public DisplayWindSpeed(int windSpeed){
 this.windSpeed = windSpeed;
 }

public void Display(){
 System.out.println("The current wind speed is: " + windSpeed + " meters per second.");
 }
}

Here because of delegating the responsibilities for each classes, each class have one responsibility hence each have exact one reason to change it

Advertisements