✏️9.1 변수 쪼개기 (Split Variable)

리팩터링 전

let temp = 2 * (height + width);
console.log(temp);
temp = height * width;
console.log(temp);

리팩터링 후

const perimeter = 2 * (height + width);
console.log(perimeter);
const area = height * width;
console.log(area);

🧷 배경

변수는 긴 코드의 결과를 저장했다가 나중에 쉽게 참조하려는 목적으로 흔히 쓰인다. 이런 변수에는 값을 단 한번만 대입해야 한다. 대입이 두 번 이상 이뤄진다면 여러 가지 역할을 수행한다는 것이다.

역할이 둘 이상인 변수가 있다면 쪼개야 한다. 여러 용도로 쓰인 변수는 코드를 읽는 이에게 커다란 혼란을 주기 때문이다.

🧷 절차

  1. 변수를 선언한 곳과 값을 처음 대입하는 곳에서 변수 이름을 바꾼다.

  2. 가능하면 이 때 불변으로 선언한다.

  3. 이 변수에 두 번째로 값을 대입하는 곳 앞까지의 모든 참조를 새로운 변수 이름으로 바꾼다.

  4. 두 번째 대입 시 변수를 원래 이름으로 다시 선언한다.

  5. 테스트한다.

  6. 마지막 대입까지 반복한다.

🧷 예시: 입력 매개변수의 값을 수정할 때

function discount (iniputValue, quantity) {
    if (inputValue > 50) inputValue = inputValue - 2;
    if (quantity > 100) inputValue = inputValue - 1;
    return inputValue;
}

inputValue가 1️⃣ 함수에 데이터를 전달하는 용도와 2️⃣ 결과를 호출자에 반환하는 용도로 쓰였다.

  1. inputValue를 쪼갠다.

function discount (originalInputValue, quantity) {
    let inputValue = originalInputValue;
    if (inputValue > 50) inputValue = inputValue - 2;
    if (quantity > 100) inputValue = inputValue - 1;
    return inputValue;
}
  1. 변수 이름 바꾸기를 두 번 수행해서 각각의 쓰임에 어울리는 이름을 지어준다.

function discount (inputValue, quantity) {
    let result = inputValue;
    if (inputValue > 50) result = result - 2;
    if (quantity > 100) result = result - 1;
    return result;
}

Last updated