一、重新组织函数
1.1、Extract Method (提炼函数)
befor:
void pringOwing(double amount){
printBanner();
//print detail
System.out.println("name:"+_name);
System.out.println("amount:"+amount);
}
after:
void pringOwing(double amount){
printBanner();
printDetails(amount);
}
void printDetails(double amount){
System.out.println("name:"+_name);
System.out.println("amount:"+amount);
}
1.2、Inline Method(内联函数)
before:
void getRating(){
return (moreThanFiveLateDeliveries()) ? 2 : 1;
}
boolean moreThanFiveLateDeliveries(){
return _numberOfLateDeliveries > 5;
}
after:
void getRating(){
return (_numberOfLateDeliveries > 5) ? 2 : 1;
}
1.3、Inline Temp (内联临时变量)
before:
double basePrice = anOrder.basePrice();
return (basePrice>1000);
after:
return (anOrder.basePrice()>1000);
1.4、Replace Temp With Query (以查询代替临时变量)
before:
double basePrice = _quantity * _itemPrice;
if (basePrice > 1000)
return basePrice * 0.95;
else
return basePrice * 0.98;
after:
if (basePrice() > 1000)
return basePrice() * 0.95;
else
return basePrice() * 0.98;
double basePrice(){
return _quantity * _itemPrice;
}
1.5、Introduce Explaining Variable (引入解释性变量)
if ((platorm.toUpperCase().indexOf("MAC")>-1) &&
(platorm.toUpperCase().indexOf("IE")>-1) &&
wasInitialized() && resize >0
)
{
//do something
}
after:
boolean isMacOs = platorm.toUpperCase().indexOf("MAC")>-1;
boolean isIEBrowers = platorm.toUpperCase().indexOf("IE")>-1;
boolean wasResize = resize > 0;
if (isMacOs && isIEBrowers && wasInitialized() && wasResize){
//do something
}