Setter 의 문제점
- 객체의 불변성 깨짐: Setter를 통해 객체의 상태를 언제든지 변경할 수 있게 되면, 객체의 불변성이 깨지고 예측하기 어려운 상태가 될 수 있다.
- 객체의 일관성 손실: 객체가 일관된 상태를 유지하는 것이 어려워진다. 객체가 유효한 상태로 생성된 후에도 외부에서 상태를 변경할 수 있기 때문이다.
- 스레드 안전성 문제: 여러 스레드에서 동일한 객체에 접근하여 상태를 변경할 때, 동시성 문제가 발생할 수 있다.
- 캡슐화 위배: 객체의 내부 구현이 외부로 노출되며, 객체 스스로 상태를 관리하는 능력이 약해진다.
Setter 외 객체 값을 설정하는 방법
생성자를 통한 값 설정
객체 생성 시 필요한 모든 값을 생성자를 통해 전달함으로써 객체의 일관성을 보장할 수 있다.
public class User {
private final String name;
private final String email;
public User(String name, String email) {
this.name = name;
this.email = email;
}
// 필요한 경우, getter 메소드를 제공
}
빌더 패턴 사용
복잡한 객체를 생성할 때 빌더 패턴을 사용하면, 코드의 가독성을 높이고 객체의 일관성을 유지할 수 있다.
public class User {
private String name;
private String email;
private User(Builder builder) {
this.name = builder.name;
this.email = builder.email;
}
public static class Builder {
private String name;
private String email;
public Builder withName(String name) {
this.name = name;
return this;
}
public Builder withEmail(String email) {
this.email = email;
return this;
}
public User build() {
return new User(this);
}
}
}
실제 애플리케이션 적용 예시
스프링 애플리케이션에서 엔티티 클래스를 설계할 때, 위와 같은 방법을 적용하면, 객체의 일관성과 안전성을 크게 향상시킬 수 있다. 예를 들어, 사용자 관리 시스템에서 User 엔티티를 다음과 같이 정의할 수 있다:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
protected User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// 필요한 경우, getter 메소드를 제공
}
엔티티에서 setter 메소드의 남용은 객체의 일관성과 안전성을 해칠 수 있다.
'Java, Spring' 카테고리의 다른 글
| [Spring] multipart로 파일 보낼때 dto로 보내는 법(muiltipart null로하면 에러날 때) (0) | 2022.02.09 |
|---|---|
| [Spring] js, css를 못찾는 404 에러 해결법 (0) | 2022.01.22 |
| [Spring Boot] 필터(Filter)와 인터셉터(Interceptor)의 차이 (0) | 2021.01.21 |
| [Spring Boot] AOP(Aspect-Oriented Programming, 관점 지향 프로그래밍) (0) | 2021.01.21 |
| [Spring Boot] @Component 와 @Bean의 차이 (0) | 2021.01.21 |