[코드리뷰 스터디 - 🚗 자동차 경주] Getter와 Setter의 적절한 위치 고민

Hyunjoon Choi·2023년 10월 1일
0

코드리뷰 스터디

목록 보기
5/5
post-thumbnail

Getter와 Setter

흔히 클래스가 가지고 있는 필드값들을 가져오거나 설정할 때 쓰이는 메서드들을 각각 Getter, Setter 메서드라 한다. 또는 접근 제어자라고 하기도 한다.

public class Car {

    private static final int START_DISTANCE = 0;
    private static final int ACCELERATE_MINIMUM_VALUE = 4;
    private static final int ACCELERATE_MAXIMUM_VALUE = 9;

    private final Name name;
    private int distance;

    private Car(final Name name, final int distance) {
        this.name = name;
        this.distance = distance;
    }

    public static Car createDefault(Name name) {
        return new Car(name, START_DISTANCE);
    }
    
    // 기타 메서드들

    // 자동차 경주 미션에서는 getter만 사용했다.
    public String getName() {
        return name.getName();
    }

    public int getDistance() {
        return this.distance;
    }
    
    // 기타 메서드들: 즉, getter가 맨 아래가 아니었다.
}

그런데, getter 메서드 (setter 포함)는 클래스의 맨 아레에 두라는 리뷰를 받았다. 왜 이렇게 말씀하셨는지 알아보자.

컨벤션으로 정의되어 있는가?

사실 많이 참고했던 구글 자바 컨벤션이나, 클린 코드 (Clean Code) 책에는 getter, setter를 맨 아래에 두라는 내용은 없다.

컨벤션은 없지만, 관례적으로 사용한다.

그런데 스택오버플로우 글을 보면, 많은 사람들이 getter와 setter를 관례상 아래에 둠을 알 수 있다.

Not sure if there is universally accepted standard but my own preferences are;

  • constructors first
  • static methods next, if there is a main method, always before other static methods
  • non static methods next, usually in order of the significance of the method followed by any methods that it calls. This means that public methods that call other class methods appear towards the top and private methods that call no other methods usually end up towards the bottom
  • standard methods like toString, equals and hashcode next
  • getters and setters have a special place reserved right at the bottom of the class

정확한 이유

컨벤션으로 이루어진 게 없는데 왜 사람들이 맨 아래에 두는 것인지 궁금하여 더 여쭤봤더니, 이유를 얻을 수 있었다.

  • getter 같은 부분은 쓰는 일이 많고 안 쓸 수 있다면 지양하는 편이 좋기 때문에 명시적으로 아래에 위치한다.
  • 불필요한 getter는 없애기 위해서 아래쪽에서 사용하는 것이 좋다.

추가 참고: 클린 코드에서의 클래스 체계 권장안

클린 코드에서 작성된 클래스 체계를 보면, 다음과 같다.

클래스를 정의하는 표준 자바 관례에 따르면, 가장 먼저 변수 목록이 나온다. 정적 (static) 공개 (public) 상수가 있다면 맨 처음에 나온다. 다음으로 정적 비공개 (private) 변수가 나오며, 이어서 비공개 인스턴스 변수가 나온다. 공개 변수가 필요한 경우는 거의 없다.
변수 목록 다음에는 공개 함수가 나온다. 비공개 함수는 자신을 호출하는 공개 함수 직후에 넣는다. 즉, 추상화 단계가 순차적으로 내려간다. 그래서 프로그램은 신문 기사처럼 읽힌다.

비공개 함수와의 위치 충돌을 피하기 위해, 접근 제어자 함수는 맨 아래에 위치하고 그 이외의 공개 함수는 모두 그 위에 작성하도록 하자.

부족하거나 보완할 점이 있다면 댓글 부탁드립니다 😃

profile
개발을 좋아하는 워커홀릭

0개의 댓글