반응형
이 내용은 코드 리뷰 스터디를 했던 당시 벨로그에 작성했었던 내용입니다.
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 other class methods appear towards the top and private methods that call no ohter 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) 변수가 나오며, 이어서 비공개 인스턴스 변수가 나온다. 공개 변수가 필요한 경우는 거의 없다.
변수 목록 다음에는 공개 함수가 나온다. 비공개 함수는 자신을 호출하는 공개 함수 직후에 넣는다. 즉, 추상화 단계가 순차적으로 내려간다. 그래서 프로그램은 신문 기사처럼 읽힌다.
비공개 함수와의 위치 충돌을 피하기 위해, 접근 제어자 함수는 맨 아래에 위치하고 그 이외의 공개 함수는 모두 그 위에 작성하도록 해야겠다는 생각을 하게 되었습니다.
부족하거나 보완할 점이 있다면 언제든지 댓글 부탁드립니다!
반응형
'🤔 고민점' 카테고리의 다른 글
[Spring] Repository의 반환 타입으로는 어떤 것을 써야 할까? (Entity vs void) (2) | 2024.02.06 |
---|