워밍업 클럽 4기 - 백엔드 Day 4 미션
6개월 전
1. 아래 코드와 설명을 보고, [섹션 3. 논리, 사고의 흐름]에서 이야기하는 내용을 중심으로 읽기 좋은 코드로 리팩토링해 봅시다.
import java.util.List;
import java.util.logging.Logger;
class Order {
private final List<Item> items;
private final Customer customer;
public Order(List<Item> items, Customer customer) {
this.items = items;
this.customer = customer;
}
public boolean hasNoItem() {
return items == null || items.isEmpty();
}
public boolean isTotalPriceInvalid() {
return calculateTotalPrice() <= 0;
}
public int calculateTotalPrice() {
if (items == null) return 0;
return items.stream()
.mapToInt(Item::calculatePrice)
.sum();
}
public boolean hasNoCustomerInfo() {
return customer == null;
}
}
class Item {
private final int price;
private final int quantity;
public Item(int price, int quantity) {
this.price = price;
this.quantity = quantity;
}
public int calculatePrice() {
return price * quantity;
}
}
class Customer { }
class OrderValidator {
private Logger log;
public boolean validate(Order order) {
if (order.hasNoItem()) {
log.info("주문 항목이 없습니다.");
return false;
}
if (order.isTotalPriceInvalid()) {
log.info("올바르지 않은 총 가격입니다.");
return false;
}
if (order.hasNoCustomerInfo()) {
log.info("사용자 정보가 없습니다.");
return false;
}
return true;
}
}
참고: Readable Code: 읽기 좋은 코드를 작성하는 사고법 세션 3
2. SOLID에 대하여 자기만의 언어로 정리해 봅시다.
SRP (단일책임 원칙)
single responsibility principle
하나의 클래스는 하나의 책임(관심사)만 갖는다.
메서드에서 하나의 역할을 가져야 하는 것과 유사한 개념
한 클래스의 책임이 두가지 이상이라면 유지보수하기가 어렵다. -> 변경 가능성이 높아진다!
OCP (개방폐쇠 원칙)
open-closed principle
확장(다형성)에는 열려 있고, 수정(코드 변경)에는 닫혀 있다.
기존 코드의 변화가 많지 않게 시스템을 확장할 수 있어야 한다!
LSP (리스코프 치환 원칙)
Liskov substitution principle
부모 클래스의 인스턴스를 자식 클래스의 인스턴스로 치환할 수 있어야 한다.
자식 클래스는 부모 클래스의 책임을 준수해야 한다!
부모의 기능을 모두 갖춘 채 확장해야 한다!
ISP(인터페이스 분리 원칙)
interface substitution principle
인터페이스의 기능 단위로 쪼개야 한다.
인터페이스 안에 내가 사용하지 않는 기능이 들어 있으면 안된다.
DIP(의존성 역전 원칙)
dependency inversion principle
상위 수준의 모듈이 하위 수준의 모듈에 의존해서는 안 된다.
추상화 레벨이 높은 쪽에서 추상화 레벨이 낮은 쪽(구체화)에 의존하면 안된다!
의존성: 하나의 모듈이 다른 하나의 모듈을 알고 있거나 직접적으로 생성하거나 사용하는 것
댓글을 작성해보세요.