상세 컨텐츠

본문 제목

10. 조건부 로직 간소화

🍜개발자라면/책을 읽자✍

by :Eundms 2021. 11. 4. 09:48

본문

10.1 조건문 분해하기

if(!aDate.isBefore(plan.summerStart)&&!aDate.isAfter(plan.summerEnd))
    charge = quantity*plan.summerRate;
else
    charge = quantity*plan.regularRate+plan.regularserviceCharge;
    
// 조건문 분해하기 적용
if(summer())
    charge = summercharge();
else
    charge = regularCharge();

10.2 조건식 통합하기

동일한 의미의 값을 조건식으로 return 한다면 통합한다.

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

// 조건식 통합하기
if (isNotEligibleForDisability())return 0;
function isNotEligibleForDisability(){
    return ((anEmployee.seniority<2)||(anEmployee.monthsDisabled>12)||(anEmployee.isPartTime));
}

10.3 중첩 조건문을 보호 구문으로 바꾸기

function getPayAmount(){
	let result;
    if (isDead)
    	result= deadAmount();
    else {
        if(isseparated)
            result = separatedAmount();
        else{
            if(isRetired)
                result = retiredAmount();
            else
                result = normalPayAmount();
        }
    }
    return result;
}

// 중첩조건문을 보호 구문으로 바꾸기
function getPayAmount(){
    if(isDead) return deadAmount();
    if(isseparated) return separatedAmount();
    if(isRetired) return retiredAmount();
    return normalPayAmount();
}

10.4 조건부 로직을 다형성으로 바꾸기

switch(bird.type){
   case '유럽 제비':
       return '보통이다';
   case '아프리카 제비':
       return (bird.numberOfCoconuts>2)?'지쳤다':'보통이다';
   case '노르웨이 파랑 앵무':
       return (bird.voltage>100)?'그을렸다':'예쁘다';
   default:
       return '알 수 없다';
}

// 조건부 로직을 다형성으로 바꾸기
class Bird{
    constructor(birdObject){
        Object.assign(this,birdObject);
    }
    get plumage(){
        return '알 수 없다';
    }
    get airSpeedVelocity(){
        return null;
    }
}
class EuropeanSwallow extends Bird{
   get plumage(){
       return '보통이다';
   }
   get airSpeedVelocity(){
       return 35;
   }
}
....

10.5. 특이 케이스 추가하기

if (aCustomer==='미확인 고객') customerName = '거주자';

// 특이 케이스 추가하기
class UnknownCustomer{
    get name(){return '거주자';}
}

10.6 어서션 추가하기

 

10.7 제어 플래그를 탈출문으로 바꾸기

for(const p of people){
    if(!found){
       if(p==='조커'){
           sendAlert();
           found=true;
       }
    }
}
//제어 플래그를 탈출문으로 바꾸기
for(const p of people){
    if(p==='조커'){
        sendAlert();
        break;
    }
}

관련글 더보기

댓글 영역