get basePrice() {this._quantity * this._itemPrice;}
...
if (this.basePrice > 1000)
return this.basePrice * 0.95;
else
return this.basePrice * 0.98;
🧷 배경
함수 안에서 결괏값을 다시 참조할 목적으로 임시 변수를 쓰기도 하는데 이는 계산 코드의 반복을 줄이고 값의 의미를 설명할 수 있어 유용하지만 함수로 만들어 사용하는 편이 나을 때가 많다.
추출한 함수에서 별도로 변수를 따로 전달할 필요가 없어 추출한 함수와 원래 함수와의 경계를 더 분명히 할 수 있다. 이로써 부자연스러운 의존 관계나 부수효과를 찾고 제거하는데 좋다.
변수에 값을 한번 대입하고 더 복잡한 코드에 다시 대입하는 경우는 모두 질의 함수로 추출해야한다.
🧷 절차
변수가 사용되기 전에 값이 확실히 결정되는지, 변수를 사용할 때마다 계산 로직이 매번 다른 결과를 내지는 않는지 확인한다.
읽기전용으로 만들 수 있는 변수는 읽기전용으로 만든다.
테스트한다.
변수 대입문을 함수로 추출한다.
➡️ 변수와 함수가 같은 이름을 가질 수 없다면 함수 이름을 임시로 짓는다. 또한, 추출한 함수가 부수효과를 일으키지는 않는지 확인한다. 부수효과가 있다면 질의 함수와 변경 함수 분리하기로 대처한다.
테스트한다.
변수 인라인하기로 임시변수를 제거한다.
🧷 예시
// Order 클래스...
constructor(quantity, item){
this._quantity = quantity;
this._item = item;
}
get price(){
var basePrice = this._quantity * this._item.price;
var discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return baseprice * discountFactor;
}
임시 변수인 basePrice와 discountFactor를 메서드로 바꾸면 아래와 같다.
// 먼저 basePrice에 const를 붙여 읽기전용으로 만들고 테스트를 해본다.
// Order클래스...
constructor(quantity, item){
this._quantity = quantity;
this._item = item;
}
get price():{
const basePrice = this._quantity * this._item.price;
var discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
그리고 다음 대입문의 우변을 게터로 추출한다.
// Order 클래스...
get price(){
const basePrice = this.basePrice;
var discountFactor = 0.98;
if (basePrice > 1000) discountFactor -= 0.03;
return basePrice * discountFactor;
}
get basePrice(){
return this._quantity * this._item.price;
}
테스트를 했다면 변수를 인라인한다. basePrice를 제거할 수 있게 된다.
// Order 클래스...
get price(){
const basePrice = this.basePrice; //삭제
var discountFactor = 0.98;
if (this.basePrice > 1000) discountFactor -= 0.03;
return this.basePrice * discountFactor;
}
discountFactor 변수도 같은 순서로 처리해준다.
// 먼저 함수추출하기를 한다.
// Order 클래스...
get price(){
const discountFactor = this.discountFactor;
return this.basePrice * discountFactor;
}
get discountFactor(){
var discountFactor = 0.98;
if (this.basePrice > 1000) discountFactor -= 0.03;
return discountFactor;
}
마지막으로 변수를 인라인한다.
// Order 클래스...
get price(){
return this.basePrice * this.discountFactor;
}