✏️6.3 변수 추출하기 ( Extract Variable)

↔️ 변수 인라인하기

return order.quantity * order.itemPrice -
  Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 +
  Math.max(order.quantity * order.itemPrice * 0.1, 100);

리팩터링 후

const basePrice  order.quantity * ordeer.itemPrice;
const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;
const shipping = Math.max(order.quantity * order.itemPrice * 0.1, 100);
return basePrice - quantityDiscount + shipping;

🧷 배경

표현식이 너무 복잡해서 이해하기 어려운 경우 지역변수를 활용하여 표현식을 쪼개 관리하기 쉽게 만들 수 있다. 이 과정에서 추가한 변수는 디버깅에 도움이 된다.

🧷 절차

  1. 추출하려는 표현식에 부작용은 없는지 확인한다.

  2. 불변 변수를 하나 선언하고 이름을 붙일 표현식의 복제본을 대입한다.

  3. 원본 표현식을 새로 만든 변수로 교체한다.

  4. 테스트한다.

  5. 표현식을 여러 곳에서 사용한다면 각각 새로 만든 변수로 교체한다. 하나 교체할 때마다 테스트한다.

🧷 리팩터링 전

function price(order) {
  // 가격(price) = 기본 가격 - 수량 할인 + 배송비
  return order.quantity * order.itemPrice - Math.max(0, order.quantity - 500) 
    * order.itemPrice * 0.05 
    + Math.min(order.quantity * order.itemPrice * 0.1, 100);
}
  1. 기본 상품 가격은 상품 가격 * 수량이다.

function price(order) {
  // 가격(price) = 기본 가격 - 수량 할인 + 배송비
  return order.quantity * order.itemPrice - 
    Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + 
    Math.min(order.quantity * order.itemPrice * 0.1, 100);
}
  1. 기본 가격을 담을 변수를 만들고 적절한 이름을 지어준다.

function price(order) {
  // 가격(price) = 기본 가격 - 수량 할인 + 배송비
  const basePrice = order.quantity * order.itemPrice;
  return basePrice - 
    Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + 
    Math.min(basePrice * 0.1, 100);
}
  1. 수량 할인, 배송비도 추출하고 교체한다.

🧷 리팩터링 후

function price(order) {
  const basePrice = order.quantity * order.itemPrice;
  const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05;
  const shipping = Math.min(basePrice * 0.1, 100);
  return basePrice - quantityDiscount + shipping;
}

주석을 지워준다. 코드로 드러나기 때문이다.

Last updated