프로그래밍/Refactoring

Substitute Algorithm

암초보 2011. 9. 19. 04:04

※ 알고리즘을 보다 명확한 것으로 바꾸고 싶을 때는, 메소드의 몸체를 새로운 알고리즘으로 바꾼다.

※ 절차
1. 대체 알고리즘을 준비하여 적용후 컴파일
2. 알고리즘 테스트. 만약 결과가 같다면 작업은 끝
3. 만약 결과가 같지 않다면, 테스트에서 비교하기 위해 예전의 알고리즘을 사용하여 디버깅

Before
String findPerson(String[] people) {
  for (int i=0; i<people.length; i++) {
    if(people[i].equals("Don")) {
      return "Don";
    }
    if(people[i].equals("John")) {
      return "John";
    }
    if(people[i].equals("Kent")) {
      return "Kent";
    }
  }
  return " ";
}


After
String findPerson(String[] people) {
  List candidates = Arrays.asList(new String[] {"Don", "John", "Kent"});
  for (int i=0; i<people.length; i++) {
    if(candidates.contains(people[i]))
      return people[i];
  }
  return " ";
}



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