상세 컨텐츠

본문 제목

6.3. 변수 추출하기

🍜개발자라면/책을 읽자✍

by :Eundms 2021. 9. 26. 14:36

본문

- 표현식이 너무 복잡해서 이해하기 어려울 때

 

표현식에 이름을 붙이고 싶다.
현재 함수 안에서만 의미가 있다? : 변수로 추출
함수를 벗어난 넓은 문맥에서까지 의미가 있다? : 함수로 추출_ 질의함수로서 사용

방법

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);
}

// 변경후
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;
}

  클래스 안에서 추출하기  

price() 메서드의 범위를 넘어 주문을 표현하는 Order 클래스 전체에 적용
/* 
	이름이 가격을 계산하는 price()의 메서드 범위를 넘어, 
	주문을 표현하는 order 클래스 전체에 적용된다.
*/
class Order {
    constructor(aRecord){
       this._data = aRecord;
    }
    get quantity() {return this._data.quantity;}
    get itemPrice() {return this._data.itemPrice;}
    get price(){
        return this.quantity*this.itemPrice 
        - Math.max(0, this.quantity-500)*this.itemPrice*0.05
        + Math.min(this.quantity*this.itemPrice*0.1, 100);
    }
}

// 변경후 ==> 함수로 추출하고 질의함수로서 사용한다.
class Order {
    constructor(aRecord){
       this._data = aRecord;
    }
    get quantity() {return this._data.quantity;}
    get itemPrice() {return this._data.itemPrice;}
    get price(){
        return this.basePrice - this.quantityDiscount + this.shipping ;
    }
    get basePrice(){return this.quantity*this.itemPrice}
    get quantityDiscount(){return Math.max(0, this.quantity-500)*this.itemPrice*0.05}
    get shipping(){return Math.min(this.quantity*this.itemPrice*0.1, 100)}
}

 

 

 

관련글 더보기

댓글 영역