《重构-改善既有代码的设计》学习笔记---Replace Temp with Query(以查询取代临时变量)

临时变量的问题在于:函数

它们是暂时的,并且只能在所属函数内使用。因为临时变量只在所属函数内可见,因此,若是不少地方都在用这个临时变量,就会驱使你写出更长的函数。若是把临时变量替换为一个查询,那么其余函数中均可以得到这份信息。spa

以查询取代临时变量是提炼函数以前必不可少的一个步骤。局部变量会使代码难以被提炼,因此应该尽量把他们替换为查询式。code

这个重构手法较为简单的状况是:临时变量只被赋值一次或者赋值给临时变量的表达式不受其余条件影响。blog

示例:get

初始代码为(2个临时变量):it

function getPrice () {
    var basePrice = _quantity * _itemPrice;
    var discountFactor;
    if(basePrice > 100){
        discountFactor = 0.95;
    } else {
       iscountFactor = 0.98;
    }
    return basePrice * discountFactor;
}        

一、把赋值动做的右侧表达式提炼出来io

function getPrice () {
    var basePrice = basePrice();
    var discountFactor;
    if(basePrice > 100){
        discountFactor = 0.95;
    } else {
       iscountFactor = 0.98;
    }
    return basePrice * discountFactor;
} 

function basePrice () {
    return  _quantity * _itemPrice;
}

二、替换临时变量的引用点,,并删除临时变量的声明。function

function getPrice () {
    var discountFactor;
    if(basePrice() > 100){
        discountFactor = 0.95;
    } else {
       iscountFactor = 0.98;
    }
    return basePrice() * discountFactor;
} 

function basePrice () {
    return  _quantity * _itemPrice;
}

三、用相似的办法,提炼另一个临时变量class

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

function basePrice () {
    return  _quantity * _itemPrice;
}

function discountFactor () {
     if(basePrice() > 100){
        return 0.95;
    } else {
      return 0.98;
    }
}

若是没有把basePrice替换为一个查询式,很难提炼discountFactor(),须要手动传入basePrice做为参数。变量

 

我的感悟:

以一个临时变量保存某一表达式的运算结果,若是这个临时变量在多个地方用到,能够考虑用此方法,将表达式提炼到一个独立函数中。

相关文章
相关标签/搜索