inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

인프런 워밍업클럽 4기 BE- 클린코드&테스트 DAY4 과제 (SOLID 원칙과 리팩토링)

qwsa7896
0

<변환 전 코드>

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;
}

<변환된 코드>

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


record Item(int price) {}
record Customer(String name) {}

class Order {
    private final List<Item> items;
    private final Customer   customer;

    Order(List<Item> items, Customer customer) {
        this.items    = items;
        this.customer = customer;
    }


    void validate() {
        if (items.isEmpty())            throw ex("주문 항목이 없습니다.");
        if (totalPrice() <= 0)          throw ex("올바르지 않은 총 가격입니다.");
        if (customer == null)           throw ex("사용자 정보가 없습니다.");
    }


    private int totalPrice() { return items.stream().mapToInt(Item::price).sum(); }
    private IllegalStateException ex(String msg) { return new IllegalStateException(msg); }
}


class OrderValidator {
    private static final Logger log = LoggerFactory.getLogger(OrderValidator.class);

    boolean validateOrder(Order order) {
        if (order == null) { log.info("주문 정보가 없습니다."); return false; }

        try { order.validate(); return true; }
        catch (IllegalStateException e) { log.info(e.getMessage()); return false; }
    }
}

 

SOLID 원칙

단일 책임 원칙 (Single Responsibility Principle, SRP)

개방-폐쇄 원칙 (Open/Closed Principle, OCP)

리스코프 치환 원칙 (Liskov Substitution Principle, LSP)

인터페이스 분리 원칙 (Interface Segregation Principle, ISP)

의존 역전 원칙 (Dependency Inversion Principle, DIP)

 

 

 

 

 

 

 

백엔드 워밍업클럽 워밍업클럽4기 BE

답변 0