자바) Setter의 사용성
자바를 공부하면서 객체지향 개념에 대해서 배우면서 캡슐화, 상속, 추상화, 다형성 4가지 개념이 핵심 개념인 것을 배울텐데
오늘은 캡슐화의 주요 기능인 getter와 setter 중 setter에 대해서 설명을 하려고 한다.
결론부터 얘기하면, Setter의 사용을 지양하라는 말이다.
먼저 계산기 프로젝트를 했을때, 계산기 클래스에서 연산을 하는 메서드가 있었고, 연산 결과를 저장하는 컬렉션 필드가 있었다.
컬렉션 필드 같은 경우, 거의 대부분 setter를 사용할 일이 없다고 한다.
public class Calculator {
private List<Double> resultList = new ArrayList<>();
public double arithmeticOperation(int firstInputNum, int lastInputNum, char operator) {
double result;
switch (operator) {
case '+' -> result = firstInputNum + lastInputNum;
case '-' -> result = firstInputNum - lastInputNum;
case '*' -> {
if (lastInputNum == 0) {
throw new IllegalArgumentException("0으로 곱할 수 없습니다.");
} else {
result = firstInputNum * lastInputNum;
}
}
case '/' -> {
if (lastInputNum == 0) {
throw new IllegalArgumentException("0으로 나눌 수 없습니다.");
} else {
result = (double) firstInputNum / lastInputNum;
}
}
default -> throw new IllegalArgumentException("잘못된 연산자입니다.");
}
// 연산 결과를 컬렉션에 저장
resultList.add(result);
return result;
}
public List<Double> getResultList(){
if (resultList.isEmpty()) {
throw new IndexOutOfBoundsException("저장된 연산 결과가 없습니다.");
}
return resultList;
}
public void removeResultList() {
// 연산결과가 비어 있을 때 삭제하면 예외
if (resultList.isEmpty()) {
throw new IndexOutOfBoundsException("저장된 연산 결과가 없습니다.");
}
resultList.remove(0);
}
}
연산을 하는 메서드에서 연산결과를 resultList.add(result); 를 통해서 컬렉션에 add를 해주고, getter를 통해서 resultList를 조회하는 메서드가 있는 상황.
결론적으로 setResultList 메서드가 불필요한 이유는 클래스 내의 resultList 필드는 내부에서 관리되고 외부에서 직접 변경하는 Setter는 필요가 없기 때문.
resultList는 arithmeticOperation 메서드를 통해 연산 결과가 추가되거나, removeResultList를 통해 삭제되는 방식으로 조작됨.
캡슐화 원칙을 따르는 것으로, 객체의 상태는 외부에서 직접 변경되지 않고, 객체 내부의 메서드를 통해서만 변경되는 것이 바람직 하다.
따라서, setResultList 메서드를 통해 외부에서 resultList를 임의로 변경하게 되면 객체의 무결성이 깨질 수 있다.
또한, resultList는 이미 클래스 내부에서 적절하게 관리되고 있으므로 굳이 외부에서 설정할 필요가 없다.