SRP(Single Responsibility Principle)
단일 책임 원칙이란 모든 클래스는 하나의 책임만 가지며, 클래스는 그 책임을 완전히 캡슐화해야 한다는 것을 말한다. 여기서 말하는 책임이란 클래스나 모듈을 변경하려는 이유를 의미한다. 다시 말해 어떤 클래스나 모듈은 변경하려는 단 하나의 이유만을 가져야 한다고 볼 수 있다.
단일 책임 원칙은 응집도는 높게, 결합도는 낮게 설계하는 것이다. 단일 책임 원칙의 장점은 책임을 분명히 하여 다른 책임의 변경으로부터 자유로워진다는 것이다. 또한 복잡도를 줄이므로 발생할 버그에 쉽게 대처할 수 있게 된다. 만약 클래스나 모듈마다 책임이 불분명하면 테스트해야 할 것이 많아져 놓칠 수 있는 부분이 많아진다.
SRP의 예시를 살펴보자.
public class Product {
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public void updatePrice(int price) {
this.price = price;
}
}
public class ProductManager {
public void update(Product product, int price) {
// validate price
validatePrice(price);
// update price
product.updatePrice(price);
}
private void validatePrice(int price) {
if (price < 1000) {
throw new IllegalArgumentException("the price is too low");
}
}
}
price 값의 유효성 검증은 Product 클래스에서 이루어져야 하는데 ProductManager 클래스에서 이루어지고 있다. 이는 다음과 같이 수정할 수 있다.
public class Product {
private static final int MINIMUM_PRICE = 1000;
private String name;
private int price;
public Product(String name, int price) {
this.name = name;
this.price = price;
}
public void updatePrice(int price) {
validatePrice(price);
this.price = price;
}
private void validatePrice(int price) {
if (price < MINIMUM_PRICE) {
throw new IllegalArgumentException(String.format("최소가격은 %d원 이상입니다.", MINIMUM_PRICE));
}
}
}
public class ProductManager {
public void update(Product product, int price) {
//update price
product.updatePrice(price);
}
}
Reference
'객체지향' 카테고리의 다른 글
| [객체지향] 디자인 패턴 (0) | 2022.04.29 |
|---|---|
| [객체지향] SOLID(5) - DIP(의존관계 역전 원칙) (0) | 2022.03.01 |
| [객체지향] SOLID(4) - ISP(인터페이스 분리 원칙) (0) | 2022.03.01 |
| [객체지향] SOLID(3) - LSP(리스코프 치환 원칙) (0) | 2022.03.01 |
| [객체지향] SOLID(2) - OCP(개방-폐쇄 원칙) (0) | 2022.03.01 |