블로그 이미지
암초보

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

Tag

05-02 17:06
2011. 9. 19. 02:44 프로그래밍/Refactoring

※ 어떤 수식의 결과값을 저장하기 위해서 임시변수를 사용하고 있다면, 수식을 뽑아내서 메소드로 만들고, 임시변수를 참조하는 곳을 찾아 모두 메소드 호출로 바꾼다. 새로 만든 메소드에서도 사용될 수 있다.

※ Extract Method 하기 전의 필수 단계

※ 절차
1. 임시변수에 값이 한번만 대입되는지 확인 (여러번이라면 Split Temporary Variable을 먼저 적용)
2. 임시변수를 final로 선언 후 컴파일 (임시변수에 값이 한번만 대입되는지 확인)
3. 대입문의 우변을 메소드로 추출
- 처음에 메소드를  private로 선언, 이후에 판단하여 접근 권한 변경
- 추출된 메소드에 부작용이 없는지 확인 (있다면 Separate Query from Modifier를 사용)
4. 컴파일 및 테스트
5. Inline Temp 적용

Before
double getPrice() {
   int basePrice = _quantity * _itemPrice;
   double discountFactor;
   if (basePrice > 1000) discountFactor = 0.95;
   else discountFactor = 0.98;
   return basePrice * discountFactor;
}

Step 1.
double getPrice() {
   final int basePrice = _quantity * _itemPrice;
   final double discountFactor;
   if (basePrice > 1000) discountFactor = 0.95;
   else discountFactor = 0.98;
   return basePrice * discountFactor;
}

Step 2.
double getPrice() {
   final int basePrice = basePrice();
   final double discountFactor;
   if (basePrice > 1000) discountFactor = 0.95;
   else discountFactor = 0.98;
   return basePrice * discountFactor;
}

private int basePrice() {
   return _quantity * _itemPrice;
}

Step 3.
double getPrice() {
   final int basePrice = basePrice();
   final double discountFactor;
   if (basePrice() > 1000) discountFactor = 0.95;
   else discountFactor = 0.98;
   return basePrice * discountFactor;
}

private int basePrice() {
   return _quantity * _itemPrice;
}

Step 4.
double getPrice() {
   final double discountFactor;
   if (basePrice() > 1000) discountFactor = 0.95;
   else discountFactor = 0.98;
   return basePrice() * discountFactor;
}

private int basePrice() {
   return _quantity * _itemPrice;
}

Step 5.
double getPrice() {
   final double discountFactor = discountFactor();
   return basePrice() * discountFactor;
}

private int basePrice() {
   return _quantity * _itemPrice;
}

private double discountFactor() {
 if (basePrice() > 1000) return 0.95;
   else return 0.98;

}

Step 6.
double getPrice() {
   return basePrice() * discountFactor();
}

private int basePrice() {
   return _quantity * _itemPrice;
}

private double discountFactor() {
 if (basePrice() > 1000) return 0.95;
   else return 0.98;

}




//////////////////////////////////////////////////////////////////////////////////////////
출처 : 마틴 파울러의 리팩토링
//////////////////////////////////////////////////////////////////////////////////////////

'프로그래밍 > Refactoring' 카테고리의 다른 글

Split Temporary Variable  (0) 2011.09.19
Introduce Explaining Variable  (0) 2011.09.19
Inline Temp  (0) 2011.09.18
Inline Method  (0) 2011.09.18
Extract Method  (0) 2011.09.18
posted by 암초보