캡슐화 원칙 위반
예시
@Entity
public class User{
private String email;
public void setEmail(String email){
this.email = email;
}
}
c. 외부에서 user.setEmail(”[email protected]”) 처럼 임의로 변경 가능
d. 데이터 무결성(Valid Data)을 보장하기 어려움
불변성 손상
도메인 로직 보호
엔티티는 단순히 데이터를 담는 DTO가 아니라 비즈니스 로직을 갖는 객체입니다.
모든 필드를 외부에서 바꿀 수 있게 하면 도메인 규칙이 깨질 위험이 있습니다.
예시
@Entity
public class BankAccount{
private BigDecimal balance;
public void deposit(BigDecimal amount){
if(amount.compareTo(BigDecimal.ZERO) <=0) throw new IllegalArgmentException();
balance = balance.add(amount);
}
}
Builder
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class User{
private final String email;
private final String name;
provate final int age;
}
객체생성
User user =User.builder()
.email("[email protected]")
.name("민상")
.age(28)
.build();
가독성 좋은
Setter 없이 초기화 가능
검증 로직 포함
@Builder
public user (String email, String name, int age){
if(email ==null || email.isBlank()) throw new IllegalArgumentException("Email required");
if(name ==null || name.isBlank()) throw new IllegalArgumentException("Name required");
if(age < 0) throw new IllegalArgumentException("Age must be non-negative");
this.email =email;
this.name = name;
this.age = age;
}
Builder + 도메인 메서드 조합
User user =User.builder()
.email("[email protected]")
.name("민상")
.age(28)
.build();
//상태 변경은 도메인 메서드로만
user.changeEmail("[email protected]");