提炼变量
重构动机
表达式有可能非常复杂而难以阅读,这种情况下局部变量有助于将表达式分解为比较容易管理的形式。
重构前
<?php
namespace app\controller;
class Index
{
/**
* 商品对应打折:
* $discount = ['food' => 0.65, 'clothes' => 0.85, 'toy' => 0.9];
* 计算商品总额:
* 食物原价 * 折扣 + 衣服原价 * 折扣 + 玩具原价 * 折扣 - 优惠券
*/
public function calculateGoodsValue($food, $clothes, $toy, $discount, $coupons)
{
return $food * $discount['food']
+ $clothes * $discount['clothes']
+ $toy * $discount['toy']
- $coupons;
}
}
重构后
<?php
namespace app\controller;
class Index
{
/**
* 商品对应打折:
* $discount = ['food' => 0.65, 'clothes' => 0.85, 'toy' => 0.9];
* 计算商品总额:
* 食物原价 * 折扣 + 衣服原价 * 折扣 + 玩具原价 * 折扣 - 优惠券
*/
public function calculateGoodsValue($food, $clothes, $toy, $discount, $coupons)
{
$calculate_food = $food * $discount['food'];
$calculate_clothes = $clothes * $discount['clothes'];
$calculate_toy = $toy * $discount['toy'];
return $calculate_food + $calculate_clothes + $calculate_toy - $coupons;
}
}
推荐文章: