targetTemperature(aPlan)
function targetTemperature(aPlan) {
currentTemperature = thermostat.currentTemperature;
// rest of function...
targetTemperature(aPlan, thermostat.currentTemperature)
function targetTemperature(aPlan, currentTemperature) {
// rest of function...
함수 안에 두기에 거북한 참조를 발견하면 전역 변수를 참조하거나 제거하길 원하는 참조를 발견하는 경우 이 리팩터링을 진행한다. 참조를 풀어내며 책임을 호출자로 옮기는 것이다.
질의 함수를 매개변수로 바꾸면 어떤 값을 제공할지를 호출자가 알아야 한다는 단점이 생긴다. 결국 호출자가 복잡해지는데 이 문제는 결국 책임 소재를 프로그램의 어디에 배정하느냐의 문제로 귀결된다. 프로젝트를 진행하며 균형점을 잘 찾아보자.
// HeatingPlan 클래스
get targetTemperature() {
if (thermostat.selectedTemperature > this._max) return this._max;
else if (thermostat.selectedTemperature < this._min) return this._min;
else return thermostat.selectedTemperature;
}
// 호출자
if (thePlan.targetTemperature > thermostat.currentTemperature) setToHeat();
else if (thePlan.targetTemperature < thermostat.currentTemperature) setToCool();
else setOff();
// HeatingPlan 클래스
targetTemperature(selectedTemperature) {
if (selectedTemperature > this._max) return this._max;
else if (selectedTemperature < this._min) return this._min;
else return selectedTemperature;
}
// 호출자
if (thePlan.targetTemperature(thermostat.selectedTemperature) > thermostat.currentTemperature) setToHeat();
else if (thePlan.targetTemperature(thermostat.selectedTemperature) < thermostat.currentTemperature) setToCool();
else setOff();