Encapsultion(4) - Replace Temp with Query

Kerem Song·2021년 4월 6일
0

Refactoring - Study

목록 보기
17/22

Replace Temp with Query

(임시 변수를 질의 함수로 바꾸기)

Extract the assignment of the variable into a function
(함수 안의 할당된 변수를 추출하기)

const basePrice = this._quantity * this._itemPrice
if (basePrice > 1000) {
  return basePrice * 0.95
} else {
  return basePrice * 0.98
}

to

get basePrice() { return this._quantity * this._itemPrice }
//...
if (this.basePrice > 1000) {
  return this.basePrice * 0.95
} else {
  return this.basePrice * 0.98
}

Motivation

  1. Avoid duplicating the calculation logic in similar functions
    비슷한 함수들간의 중복된 연산 로직을 피할 수 있다.

Procedure
1. Verify that the value is clearly determined before the variable is used, and that the computational logic does not produce different results each time the variable is used.
변수가 사용되기 전에 값이 확실히 결정되는지, 변수를 사용할 때마다 계산 로직이 매번 다른 결과를 내지는 않는지 확인한다.

  1. Make variables to read-only one, If you can
    읽기전용으로 만들 수 있는 변수는 읽기전용으로 만든다.

  2. Test it.
    테스트한다.

  3. Extract variable statement to function
    변수 대입문을 함수로 추출한다.

  4. Test it.
    테스트한다.

  5. Remove temporary variable with that inline variable
    변수 인라인하기로 임시 변수를 제거한다.

profile
Tea and Dessert

0개의 댓글