해당 포스팅은 인프런 백기선님의 '리팩토링'을 학습 후 정리한 내용입니다.
public class Thermostats {
public static Integer targetTemperature = 70;
public static Boolean heating = true;
public static Boolean cooling = false;
public static Boolean fahrenheit = true;
public static void main(String[] args) {
System.out.println(Thermostats.targetTemperature);
Thermostats.targetTemperature = -1111600;
Thermostats.fahrenheit = false;
}
}
전역 변수인 targetTemperature 을 외부에서 변경할 수 있다.
객체 내부 필드의 접근 제한자를 private 으로 수정 후 변경 작업 시 메서드를 통해 변경하자!
public class Thermostats {
private static final Integer targetTemperature = 70;
private static Boolean heating = true;
private static Boolean cooling = false;
private static Boolean readInFahrenheit = true;
public static Integer getTargetTemperature() {
return targetTemperature;
}
public static void setTargetTemperature(Integer targetTemperature) {
//TODO validation
Thermostats.targetTemperature = targetTemperature;
}
public static Boolean getHeating() {
return heating;
}
public static void setHeating(Boolean heating) {
Thermostats.heating = heating;
}
public static Boolean getCooling() {
return cooling;
}
public static void setCooling(Boolean cooling) {
Thermostats.cooling = cooling;
}
public static Boolean getReadInFahrenheit() {
return readInFahrenheit;
}
public static void setReadInFahrenheit(Boolean readInFahrenheit) {
Thermostats.readInFahrenheit = readInFahrenheit;
}
}
모든 필드에 대해 getter, setter 를 메서드를 추가하여 필드에 직접 접근하지 않고 메서드를 통해 데이터에 접근한다. targetTemperature 는 수정이 불가능하게 final 로 바꾼다.