✏️10.2 조건식 통합하기 (Consolidate Conditional Expression)

리팩터링 전

if (anEmployee.seniority < 2) return 0;
if (anEmployee.monthsDisabled > 12) return 0;
if (anEmployee.isPartTime) return 0;

리팩터링 후

if (isNotEligableForDisability()) return 0;

function isNotEligableForDisability() {
  return ((anEmployee.seniority < 2)
          || (anEmployee.monthsDisabled > 12)
          || (anEmployee.isPartTime));
}

🧷 배경

비교하는 조건은 다르지만 그 결과로 수행하는 동작은 똑같은 코드들은 같은 일을 할 거라면 조건 검사도 하나로 통합하는게 낫다.

📍 조건부 코드를 통합하는게 중요한 이유

  • 여러 조각으로 나뉜 조건들을 하나로 통합함으로써 하는 일이 명확해진다.

  • 이 작업이 함수 추출하기까지 이어질 가능성이 높다.

조건식을 통합해야 하는 이유는 이 리팩터링을 하지 말아야 하는 이유도 설명한다.

  • 독립된 검사들이라고 판단되면 이 리팩터링을 하면 안된다.

🧷 절차

  1. 해당 조건식들 모두에 부수효과가 없는지 확인한다.

  2. 조건문 두 개를 선택하여 두 조건문의 조건식들을 논리 연산자로 결합한다.

  3. 테스트한다.

  4. 조건이 하나만 남을 때까지 2~3 과정을 반복한다.

  5. 하나로 합쳐진 조건식을 함수로 추출할지 고려해본다.

🧷 예시: or 사용하기

🧷 리팩터링 전

function disabilityAmount(anEmployee) {
  if (anEmployee.seniority < 2) return 0;
  if (anEmployee.monthDisabled > 12) return 0;
  if (anEmployee.isPartTime) return 0;
  // 장애 수단 계산
}

🧷 리팩터링 후

function disabilityAmount(anEmployee) {
  if (isNotEligibleForDisability()) return 0;
}

function isNotEligibleForDisability() {
  return ((anEmployee.seniority < 2)
          || (anEmployee.monthDisabled > 12)
          || (anEmployee.isPartTime));
}

🧷 예시: and 사용하기

🧷 리팩터링 전

if (anEmployee.onVacation)
  if (anEmployee.seniority > 10)
    return 1;
  return 5;

🧷 리팩터링 후

if ((anEmployee.onVacation)
  && (anEmployee.seniority > 10) return 1;
    return 5;

Last updated