Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

User 객체의 일관성 유지 #27

Closed
jiaeYoon opened this issue Jul 19, 2023 · 1 comment
Closed

User 객체의 일관성 유지 #27

jiaeYoon opened this issue Jul 19, 2023 · 1 comment
Assignees
Labels
invalid This doesn't seem right

Comments

@jiaeYoon
Copy link
Owner

Describe issue

User 엔티티의 @Setter 어노테이션이 객체의 일관성을 깨뜨릴 수 있음

Problematic code

@Getter
@Setter
@NoArgsConstructor
@Entity
public class User extends BaseTimeEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(columnDefinition = "varchar(30)")
    private String name;
    
    ...
}

Spring Project Setting

  • Version 2.7.11
  • Gradle 8.1.1
  • Java 11
@jiaeYoon jiaeYoon added the invalid This doesn't seem right label Jul 19, 2023
@jiaeYoon jiaeYoon self-assigned this Jul 19, 2023
@jiaeYoon
Copy link
Owner Author

jiaeYoon commented Jul 19, 2023

원인 파악
@Setter 어노테이션 때문에 User 엔티티의 필드를 어디서든 접근할 수 있다.
이에 따라 의도치 않게 user의 값을 변경하는 경우가 발생할 수 있으므로 일관성이 깨질 가능성이 높다.

@Setter를 대신할 수 있는 방법
필드 값을 객체 생성 시점에 넣어줌으로써 객체의 일관성을 유지할 수 있다.
생성자를 이용해 객체를 초기화시킬 수도 있지만 가독성이 떨어지고, 매개변수 조합마다 생성자가 필요하다는 단점이 있다.
Builder 패턴을 이용하면 가독성 있으면서, 상황에 맞는 유연한 객체 생성이 가능해진다.

적용 결과

@Builder
public User(String name, String nickname, String email, Role role) {
    this.name = name;
    this.nickname = nickname;
    this.email = email;
    this.role = role;
}
User user = User.builder()
    .name(name)
    .role(role)
    .build();

- 예를 들어 2개의 인자가 필요한 경우, 생성자는 따로 2개의 인자를 받는 생성자를 만들어줬어야 했다.
- 그러나 빌더를 사용한다면 2개의 인자만 넘기면 된다. 2개의 인자를 가지는 형태로 알아서 변형되므로 작성해야 할 코드가 줄고, 효율적으로 유지보수할 수 있다.

jiaeYoon added a commit that referenced this issue Jul 19, 2023
@jiaeYoon jiaeYoon pinned this issue Jul 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
invalid This doesn't seem right
Projects
None yet
Development

No branches or pull requests

1 participant