Single Responsibility Principle (SRP)
The Single Responsibility Principle (SRP) is one of the five object-oriented design principles that form the SOLID principles. It states that a class should have only one reason to change. In other words, a class should have only one responsibility.
Applying SRP to your code promotes modularity and maintainability. By ensuring that each class has a single responsibility, you can isolate changes related to that responsibility and minimize the impact on other parts of the codebase.
For example, let's consider a Car
class. According to SRP, the Car
class should be responsible for only one aspect of a car, such as storing and setting the car's model and color:
1class Car {
2 private String model;
3 private String color;
4
5 public void setModel(String model) {
6 this.model = model;
7 }
8
9 public void setColor(String color) {
10 this.color = color;
11 }
12}
13
14public class Main {
15 public static void main(String[] args) {
16 Car car = new Car();
17 car.setModel("Toyota Camry");
18 car.setColor("Blue");
19 }
20}
In this example, the Car
class has a single responsibility of managing the model and color of a car. If we need to make changes to how the car's model or color is handled, we only need to modify the Car
class.
By following the Single Responsibility Principle, we can make our code easier to understand, test, and maintain.
xxxxxxxxxx
class Car {
private String model;
private String color;
public void setModel(String model) {
this.model = model;
}
public void setColor(String color) {
this.color = color;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.setModel("Toyota Camry");
car.setColor("Blue");
}
}