복잡한 조건부 로직은 프로그램을 복잡하게 만든다. 코드를 부위별로 분해한 다음 해체된 코드 덩어리들을 각 덩어리의 의도를 살린 이름의 함수 호출로 바꿔주면 전체적인 의도가 더 확실히 드러난다.
// before
if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd)) {
charge = quantity * plan.summerRate;
} else {
charge = quantity * plan.regularRate + plan.regularServiceCharge;
}
// after
if (summer()) {
charge = summerCharge();
} else {
charge = quantity * plan.regularRate + plan.regularServiceCharge;
}
function summer() {
return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
}
function summerCharge() {
return quantity * plan.summerRate;
}
function regularcharge() {
return quantity * plan.regularRate + plan.regularServiceCharge;
}
비교하는 조건은 다르지만 그 결과로 수행하는 동작은 똑같은 코드들이 있다면 조건 검사도 하나로 통합하는 것이 좋다. 'and' 연산자와 'or' 연산자를 사용하면 여러 개의 비교로직을 하나로 합칠 수 있다.
조건부 코드를 통합하는 것이 중요한 이유는 두 가지다.
1. 여러 조각으로 나뉜 조건들을 하나로 통합함으로써 내가 하려는 일이 더 명확해진다.
2. 복잡한 조건식을 함수로 추출하면 코드의 의도가 훨씬 분명하게 드러난다.
// before
function disabilityAmount(anEmployee) {
if (anEmployee.seniority < 2) return 0;
if (anEmployee.monthDisabled > 12) return 0;
if (anEmployee.isPartTime) return 0;
}
// after
function disabilityAmount(anEmployee) {
if (isNotEligibleForDisability()) return 0;
}
function isNotEligibleForDisability() {
return ((anEmployee.seniority < 2)
|| (anEmployee.monthDisabled > 12)
|| (anEmployee.isPartTime));
}
TBD