1、Decompose Conditional(分解条件表达式)
重构前:
if(date.before(SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate;
重构后:
if(notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge(quantity);
2、Consolidate Conditional Expression(合并条件表达式)
重构前:
double disabilityAmount(){ if(_seniority < 2) return 0; if(_monthsDisabled > 12) return 0; if(_isPartTime) return 0; //computer the disability amount }
重构后:
double disabilityAmount(){ if(isNotEligableForDisablity()) return 0; //computer the disablity amount }
3、Consolidate Duplicate Conditional Fragments(合并重复的条件片段)
重构前:
if(isSpecialDeal()){ total = price * 0.95; send(); } else{ total = price * 0.98; send(); }
重构后:
if(isSpecialDeal()){ total = price * 0.95; } else{ total = price * 0.98; } send();
4、Remove Control Flag(移除控制标记)
在一系列布尔表达式中,某个变量带有“控制标记”(control flag)的作用。以break语句或return语句取代控制标记。
5、Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件表达式)
重构前:
double getPayAmount(){ double result; if(_isDead) result = deadAmount(); else{ if(_isSeparated) result = separatedAmount(); else{ if(_isRetired) result = retiredAmount(); else result = normalPayAmount(); } } return result; }
重构后:
double getPayAmount(){ if(_isDead) return deadAmount(); if(_isSeparated) return separatedAmount(); if(_isRetired) return retiredAmount(); return normalPayAmount(); }
6、Replace Conditional with Polymorphism(以多态取代条件表达式)
7、Introduce Null Object(引入Null对象)
8、Introduce Assertion(引入断言)