Day4 misson 1
6개월 전
GOAL : 아래 코드와 설명을 보고, [섹션 3. 논리, 사고의 흐름]에서 이야기하는 내용을 중심으로 읽기 좋은 코드로 리팩토링해 봅시다.
public boolean validateOrder(Order order) {
if (order.getItems().size() == 0) {
log.info("주문 항목이 없습니다.");
return false;
} else {
if (order.getTotalPrice() > 0) {
if (!order.hasCustomerInfo()) {
log.info("사용자 정보가 없습니다.");
return false;
} else {
return true;
}
} else if (!(order.getTotalPrice() > 0)) {
log.info("올바르지 않은 총 가격입니다.");
return false;
}
}
return true;
}
가장 좋은 코드는 Order에 검증 기능을 넣어 사용하는 객체에서 몰라도 되도록 캡슐화 하는 것이 좋다.
하지만 어떤 처리를 하는지 예측은 가능하도록 또는 가감할 수 있도록 구현은 감추고 체이닝을 도입했다.
public boolean validateOrder(Order order) {
return order.hasItems()
.isLessEqualThan(0)
.hasCustomersInfo()
.validate();
}
public class Order {
...
private boolean isValid;
public Order hasItems(){
long count = items.stream().filter(Objects::nonNull).count();
this.isValid = count > 0;
if(false == this.isValid) log.info("주문 항목이 없습니다. {}", id);
return this;
}
public Order isGreaterThan(int price) {
int totalPrice = items.stream()
.mapToInt(Item::getPrice)
.sum();
this.isValid = totalPrice > price;
if(false == this.isValid) log.info("올바르지 않은 총 가격입니다. {}", totalPrice);
return this;
}
public Order hasCustomer(){
this.isValid = hasCustomerInfo();
if(false == this.isValid) log.info("사용자 정보가 없습니다. {}", customer.toString());
return this;
}
public boolean validate(){
return this.isValid;
}
}
댓글을 작성해보세요.