# 11.6 질의 함수를 매개변수로 바꾸기

리팩터링 전

```javascript
targetTemperature(aPlan)

function targetTemperature(aPlan) {
  currentTemperature = thermostat.currentTemperature;
  // rest of function...
```

리팩터링 후

```javascript
targetTemperature(aPlan, thermostat.currentTemperature)

function targetTemperature(aPlan, currentTemperature) {
  // rest of function...
```

## 🧷 배경

함수 안에 두기에 거북한 참조를 발견하면 전역 변수를 참조하거나 제거하길 원하는 참조를 발견하는 경우 이 리팩터링을 진행한다. 참조를 풀어내며 책임을 호출자로 옮기는 것이다.

질의 함수를 매개변수로 바꾸면 어떤 값을 제공할지를 호출자가 알아야 한다는 단점이 생긴다. 결국 호출자가 복잡해지는데 이 문제는 결국 책임 소재를 프로그램의 어디에 배정하느냐의 문제로 귀결된다. 프로젝트를 진행하며 균형점을 잘 찾아보자.

## 🧷 절차

1. 변수 추출하기로 질의 코드를 함수 본문의 나머지 코드와 분리한다.
2. 함수 본문 중 해당 질의를 호출하지 않는 코드들을 별도 함수로 추출한다.
3. 방금 만든 변수를 인라인하여 제거한다.
4. 원래 함수도 인라인한다.
5. 새 함수의 이름을 원래 함수의 이름으로 고친다.

## 🧷 예시

### 🧷 리팩터링 전

```javascript
// 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();
```

### 🧷 리팩터링 후

```javascript
// 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();
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://koseoyoung.gitbook.io/library/refactoring/chapter-11-api/11.6.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
