【重构】重新组织函数

一、重新组织函数

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
}
posted @ 2019-05-06 23:13  加州风尘  阅读(267)  评论(0编辑  收藏  举报