Java Record Class

Java Record Class에 대해 간략히 소개합니다.

Java Record Class는 Java 14에서 처음 도입되어서 Java 16에서 정식으로 채택된 새로운 클래스 타입 중 하나이다. Record라는 말 그대로 불변하는 객체를 간결하게 표현하고자 생긴 Class이다.

이전에는 Constructor을 통해서만 객체의 값이 설정되고 Setter가 없는 클래스들 Value Only라고 해서 Vo 객체로 관리하는 관례가 있었는데, Record 클래스를 사용하면 코드의 Line 수를 획기적으로 줄일 수 있다.

예를 들어 SignUpRequest를 Class로 받고자 하는 시나리오를 생각해보자. 외부에서 들어오는 Request이기 때문에 Setter를 굳이 사용할 이유가 없다. 그래서 Vo 객체를 만든다.

public class SignUpRequest {
    public SignUpRequest(String name, Integer age, String email, String telephone, LocalDate birthday) {
        this.name = name;
        this.age = age;
        this.email = email;
        this.telephone = telephone;
        this.birthday = birthday;
    }

    private final String name;
    private final Integer age;
    private final String email;
    private final String telephone;
    private final LocalDate birthday;

    // 무수히 많은 Getter가 있다고 가정하자.


    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public String getEmail() {
        return email;
    }

    public String getTelephone() {
        return telephone;
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    @Override
    public String toString() {
        return "SignUpRequest{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", email='" + email + '\'' +
                ", telephone='" + telephone + '\'' +
                ", birthday=" + birthday +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || getClass() != o.getClass()) return false;
        SignUpRequest that = (SignUpRequest) o;
        return Objects.equals(name, that.name) && Objects.equals(age, that.age) && Objects.equals(email, that.email) && Objects.equals(telephone, that.telephone) && Objects.equals(birthday, that.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, email, telephone, birthday);
    }
}

기존대로 만들자면 62라인의 코드가 나오게 된다. 이걸 Record 클래스로 구성하면 아래와 같다.

public record SignUpRequest(
        String name,
        Integer age,
        String email,
        String telephone,
        LocalDate birthday
) { }

7라인으로 줄게 된다!

Record 클래스에는 이렇게 Field를 생성하면 알아서 AllArgsConstructor와 ToString(), equals(), hashCode() 메소드도 생성된다. 진정 Vo의 대체제라고 볼 수 있다.

또한 Spring Validator도 그대로 사용할 수 있으며, Custom Constructor도 생성할 수 있기 때문에 Vo를 대체할 강력한 수단임은 확실하다고 생각된다.

여러분도 Record Class를 사용하여 광명을 찾는 것은 어떨까?