【重构实例】
1.提炼函数(Extract Methods)
将代码段放入函数中,让函数名称解释该函数的用途
String name = request.getParameter("Name"); if(!isNullOrEmpty(name)){ ...... } String age = request.getParamter("Age"); if(!isNullOrEmpty(name)){ ...... } private boolean isNullOrEmpty(final String string){ if(string!=null && string.length()>0){ return true; }else{ return false; } }
int getRating(){ return (_numberOfLateDeliveries>5) ? 2 : 1; }
return (anOrder.basePrice()>1000);
if(basePrice()>1000) return basePrice()*0.95; else return basePrice()*0.98; ... double basePrice(){ return _quantity*_itemPrice; }
boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1; boolean isIEBrower = browser.toUpperCase().indexOf("IE") > -1; boolean wasResized = resize > 0; if(isMacOs && isIEBrowser && wasInitialized() && wasResized){ .... }
double temp = 2(_height+_width); System.out.println(temp); temp=_height*_width; System.out.println(temp);
重构:
double perimeter = 2*(_height+_width); System.out.println(perimeter); double area = _height*_width; Sytem.out.println(area);
double getPayAmount(){ if(...) return deadAmount(); if(...) return separatedAmount(); if(...) return retiredAmount(); return normalPayAmount(); }
8.分解条件表达式(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);