Encapsulation(9) - Substitute Algorithm

Kerem Song·2021년 4월 6일
1

Refactoring - Study

목록 보기
22/22

Substitute Algorithm

(알고리즘 대체하기)

Replace complicated algorithm with simpler algorithm
(복잡한 알고리즘을 간단한 알고리즘으로 대체하기)

function foundPerson(people) {
  for (let i = 0; i < people.lenth; i++) {
    if (people[i] === "Don") {
      return "Don"
    }
    if (people[i] === "John") {
      return "John"
    }
    if (people[i] === "Kent") {
      return "Kent"
    }
  }
  return ""
}

to

function foundPerson(people) {
  const candidates = ["Don", "John", "Kent"]
  return people.find(p => candidates.includes(p)) || ""
}

Motivation

  1. Change to algorithm which make changes easier
    The clearer algorithm is, the better.
    교체가 쉽고 명확한 알고리즘으로 교체하는 것이 더 좋다

Procedure

  1. Move code that would be changed to one function
    교체할 코드를 함수 하나에 모은다.

  2. Just use only first step's function and make a test.
    이 함수만을 이용해 동작을 검증하는 테스트를 마련한다.

  3. Prepare the algorithm to subtitute original one
    대체할 알고리즘을 준비한다.

  4. Do static check
    정적 검사를 수행한다.

  5. Perform a test comparing the results of existing and new algorithms. If the two results are the same, refactoring ends. If not, test and debug the new algorithm by referring to the existing algorithm.
    기존 알고리즘과 새 알고리즘의 결과를 비교하는 테스트를 수행한다. 두 결과가 같다면 리팩터링이 끝난다. 그렇지 않다면 기존 알고리즘을 참고해서 새 알고리즘을 테스트하고 디버깅한다.

profile
Tea and Dessert

0개의 댓글