블로그 이미지
암초보

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 10:04
2011. 9. 19. 03:32 프로그래밍/Refactoring
※ 파라미터에 값을 대입하는 코드가 있으면, 대신 임시변수를 사용하도록 하라.

※ 자바에서는 값에 의한 전달만 사용, 참조에 의한 전달은 사용 안함

※ 절차
1. 파라미터를 위한 임시변수를 만든다.
2. 파라미터에 값을 대입한 코드 이후에서 파라미터에 대한 참조를 임시변수로 바꾼다.
3. 파라미터에 대입하는 값을 임시변수에 대입하도록 바꾼다.
4. 컴파일 및 테스트

Before
int discount (int inputVal, int quantity, int yearToDate) {
   if (inputVal > 50) inputVal -= 2;
   if (quantity > 100) inputVal -= 1;
   if (yearToDate > 10000) inputVal -= 4;
   return inputVal;
}

After
int discount (int inputVal, int quantity, int yearToDate) {
   int result = inputVal;
   if (inputVal > 50) result -= 2;
   if (quantity > 100) result -= 1;
   if (yearToDate > 10000) result -= 4;
   return result;
}

More....
파라미터를 final로 선언하여 이 관례를 강제할 수 있지만,
(자바 1.1부터 파라미터를 fianl로 하는 것이 가능해짐)
짧은 메소드에 대해서는 코드를 명확하게 하는데 별로 큰도움이 되지 않으므로 사용 안함.
int discount (final int inputVal, final int quantity, final int yearToDate) {
   int result = inputVal;
   if (inputVal > 50) result -= 2;
   if (quantity > 100) result -= 1;
   if (yearToDate > 10000) result -= 4;
   return result;
}




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

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

Substitute Algorithm  (1) 2011.09.19
Replace Method with Method Object  (0) 2011.09.19
Split Temporary Variable  (0) 2011.09.19
Introduce Explaining Variable  (0) 2011.09.19
Replace Temp with Query  (0) 2011.09.19
posted by 암초보