[내배캠/TIL(6/9)]도메인 모델 패턴, 예외만들기

손홍서·2022년 6월 9일
0

Java

목록 보기
9/11

day34 TIL

도메인 모델 패턴

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "dtype")
@Getter
@Setter
public class Item {

    @Id
    @GeneratedValue
    @Column(name = "item_id")
    private Long id;

    private String name;
    private int price;
    private int stockQuantity;

    @ManyToMany(mappedBy = "items")
    private List<Category> categories = new ArrayList<>();

    //=====비지니스 로직======//

    /**
     * stock 증가
     * @param quantity
     */
    public void addStock(int quantity) {
        this.stockQuantity += quantity;
    }

    public void removeStock(int quantity) {
        int restStock = this.stockQuantity - quantity;
        if (restStock < 0) {
            throw new NotEnoughStockException("need more stock"); //만든 예외
        }
        this.stockQuantity = restStock;
    }
}

보통 위의 코드처럼 비지니스 로직을 엔티티에 넣어 관리하는 것이 좋다!
이는 객체 지향 특성을 적극 활용한 것으로 service부분에서 객체 생성 후 getter와 setter를 활용해 값을 변경하는것 보다 더 깔끔하고, 응집도도 높다.
이를 도메인 모델 패턴이라고 한다.


public class NotEnoughStockException extends RuntimeException{
    public NotEnoughStockException() {
        super();
    }

    public NotEnoughStockException(String message) {
        super(message);
    }

    public NotEnoughStockException(String message, Throwable cause) {
        super(message, cause);
    }

    public NotEnoughStockException(Throwable cause) {
        super(cause);
    }

    protected NotEnoughStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

exception package를 만들고 그 안에서 관리해주면 좋다.
주로 RuntimeException을 상속받고 함수를 override해준다.
간단하지만 앞으로 프로젝트에서 유용하게 사용할 수 있을 것 같아 간단하게 정리해보았다.

profile
Hello World!!

0개의 댓글