블로그 이미지
암초보

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 08:23
2011. 9. 19. 02:54 프로그래밍/Refactoring

※ 복잡한 수식이 있는 경우에는, 수식의 결과나 또는 수식의 일부에 자신의 목적을 잘 설명하는 이름으로 된 임시변수를 사용하라.

※ 보통 Extract Method로 해결 - 임시변수는 한 메소드의 컨텍스트 내에서만 유용하지만 메소드는 객체의 모든 부분, 다른 객체에서도 유용
※ 지역변수 때문에 Extract Method의 사용이 어려운 경우 Introduce Explaining Variable 사용

※ 절차

1. final 변수를 선언하고, 복잡한 수식의 일부를 이 변수에 대입
2. 원래의 복잡한 수식에서, 임시변수에 대입한 수식을 임시변수로 바꾼다.
3. 컴파일 및 테스트
4. 수식의 다른 부분에 대해서도 위의 작업 반복

Before

double price() {
   // price = (base price) - (quantity discount) + (shipping);
   return _quantity * itemPrice -
      Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
      Math.min(_quantity * itemPrice * 0.1, 100.0);
}

Step 1.
double price() {
   // price = (base price) - (quantity discount) + (shipping);
   final double basePrice = _quantity * itemPrice;
   return basePrice -
      Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
      Math.min(_quantity * itemPrice * 0.1, 100.0);
}


Step 2.
double price() {
   // price = (base price) - (quantity discount) + (shipping);
   final double basePrice = _quantity * itemPrice;
   return basePrice -
      Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
      Math.min(basePrice * 0.1, 100.0);
}

Step 3. (동일하게 모두 적용)
double price() {
   // price = (base price) - (quantity discount) + (shipping);
   final double basePrice = _quantity * itemPrice;
   final double quantityDiscount = Math.max(0, _quantity - 500) * _itemPrice * 0.05;
   final double shipping = Math.min(basePrice * 0.1, 100.0);
   return basePrice - quantityDiscount + shipping;
}



☞ Extract Method를 사용한 경우
Before
double price() {
   // price = (base price) - (quantity discount) + (shipping);
   return _quantity * itemPrice -
      Math.max(0, _quantity - 500) * _itemPrice * 0.05 +
      Math.min(_quantity * itemPrice * 0.1, 100.0);
}

After
double price() {
   // price = (base price) - (quantity discount) + (shipping);
   return basePrice() - quantityDiscount() + shipping();
}
private double quantityDiscount() {
   return Math.max(0, _quantity - 500) * _itemPrice * 0.05 ;
}
private double shipping() {
   return Math.min(basePrice() * 0.1, 100.0);
}
private double basePrice() {
   return _quantity * itemPrice;
}




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

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

Remove Assignments to Parameters  (0) 2011.09.19
Split Temporary Variable  (0) 2011.09.19
Replace Temp with Query  (0) 2011.09.19
Inline Temp  (0) 2011.09.18
Inline Method  (0) 2011.09.18
posted by 암초보