有一个复杂的表达式,将该复杂表达式或其中一部分的结果放进一个临时变量一次变量名称来解释表达式的用途
示例
修改前
if ($goods->inventory > 1000 && $number < 1000) {
// do something
}
修改后
$inventoryEnough = $goods->inventory > 1000;
$numberLimit = $number < 1000;
if ($inventoryEnough && $numberLimit) {
// do something
}
动机
- 表达式有可能非常复杂而难以阅读.这种情况下, 临时变量可以帮助你将表达式分解为比较容易管理的形式
- 在条件逻辑中引入解释性变量非常有价值:你可以使用这项重构将每个条件子句提炼出来.以一个良好命名的临时变量来解释对应条件子句的意义.使用这项重构的另一种情况是,在较长的算法中,可以运用临时变量来解释每一步运算的意义.
做法
- 声明临时变量,将待分解的复杂表达式的一部分动作的运算结果赋值给他
- 将表达式中的远算结果这一部分替换为上述临时变量
- 重复上述过程处理表达式的其他部分
示例
修改前:
/**
* 获取价格
* @return float
*/
public function price () {
return $this->quantity * $this->itemPrice - max(0, $this->quantity - 500) * $this->itemPrice * 0.05 + min($this->quantity * $this->itemPirce * 0.1, 100);
}
使用引入解释性变量修改后:
/**
* 获取价格
* @return float
*/
public function price () {
$basePrice = $this->quantity * $this->itemPrice;
$quantityDIscount = max(0, $this->quantity - 500) * $this->itemPrice * 0.05;
$shipping = min($basePrice * 0.1, 100);
return $basePrice - $quantityDIscount + $shipping;
}
使用提炼函数修改后:
/**
* 获取价格
* @return float
*/
public function price () {
return $this->basePrice() - $this->quantityDIscount() + $this->shipping();
}
/**
* 基础价格
* @return float|int
*/
public function basePrice(){
return $this->quantity * $this->itemPrice;
}
/**
* 折扣
* @return float
*/
public function quantityDiscount() {
return max(0, $this->quantity - 500) * $this->itemPrice * 0.05;
}
/**
* 运费
* @return mixed
*/
public function shipping() {
return min($this->basePrice * 0.1, 100);
}
可以看出,提炼函数的工作量通常不比引入解释性变量的工作量来的大.那么应该在什么时候使用引入解释性变量呢?在提炼函数需要花费更大工作量时.如果算法中拥有大量局部变量,那么使用提炼函数绝非易事,这种情况下就会使用引入解释性变量.然后再考虑下一步改怎么办?搞清楚代码逻辑之后就可以使用以查询取代临时变量将中间引入的那些解释性临时变量去掉.
网友评论