다른 사람의 코드를 보거나 내가 코드를 짜다보면 복잡한 내용이 조건문에 들어가는 경우가 있음
이 기법의 목적은 조건이 있는 함수를 추출하여 코드를 읽기 쉽게 만드는 것
class Simple_Example{
void Example(){
if(date < SUPPER_STAR || date > SUPPER_END)
charge = quantity * winterRate + winterServiceCharge;
else
charge = quantity * summerRate;
}
}
if문 안에 조건이 복잡해....
charge에 대입되는 값들도 너무 복잡해...
class Simple_Example{
void Example(){
if(isNotSummer())
charge = CalculateWinterRate();
else
charge = CalculateSummerRate();
}
}
private bool IsNotSummer(){
return date < SUPPER_STAR || date > SUPPER_END;
}
private bool CalculateWinterRate(){
return quantity * winterRate + winterServiceCharge;
}
private bool CalculateSummerRate(){
return quantity * summerRate;
}
조건들을 함수로 만들어서 대입함!
코드는 늘어났짐나 알아보기 편해짐
같은 결과를 내는 조건문이 연속된다면 하나의 조건식으로 합치는 기법
if(anEmployee.seniority < 2) return 0;
if(anEmployee.MothsDisabled > 12) return 0;
if(anEmployee.isPartTime) return 0;
if(isNotEligableForDisability()) return 0;
function isNotEligableForDisability(){
return ((anEmployee.seniority < 2)
|| (anEmployee.MothsDisabled > 12)
|| (anEmployee.isPartTime));
}
📑 References
https://arisu1000.tistory.com/27589
https://arisu1000.tistory.com/27585