Replace Temp With Query(以查询取代临时变量)

  1. boolean getPrice(){
  2. double basePrice = _quantity * _itemPrice;
  3. if (basePrice > 1000){
  4. return basePrice * 0.95;
  5. } else {
  6. return basePrice * 0.98;
  7. }
  8. }

修改后:

boolean getPrice(){
    if (basePrice() > 1000){
        return basePrice() * 0.95;
    } else {
        return basePrice() * 0.98;
    }
}

double basePrice(){
    return _quantity * _itemPrice;
}

做法

  • 找出只被赋值一次的临时变量

    如果某个临时变量被赋值超过一次,考虑使用Split Temporary Variable将它分割成多个变量

  • 将该临时变量声明为final

  • 编译

    这可确保该临时变量的值只被赋值一次

  • 将”对该临时变量赋值”之语句的等号右侧部分提炼到一个独立的函数中

    首先将函数声明为private。日后你可能会发现有更多类需要使用它,那时放松对它们的保护也很容易

确保提炼出来的函数无任何副作用,也就是说该函数并不修改任何对象内容。如果它有副作用,就对它进行Separate Query Form Modifler

  • 编译,测试

  • 在该临时变量身上实施Inline Temp

范例

double getPrice(){
    int basePrice = _quantity * _itemPrice;
    double discountFactor;
    if(basePrice > 1000){
        discountFactor = 0.95;
    }else{
        discountFactor = 0.98;
    }
    return basePrice * discountFactor;
}

修改后:

double getPrice(){
    return basePrice() * discountFactor();
}

private double discountFactor(){
    if(basePrice() > 1000){
        return  0.95;
    }else{
        return  0.98;
    }
}

private int basePrice(){
    return _quantity * _itemPrice;
}