代码对一个参数进行赋值.以一个临时变量取代该参数的位置
示例:
修改前:
/**
* 打折
* @param $inputVal
* @param $quantity
* @param $yearToDate
*/
public function discount ($inputVal, $quantity, $yearToDate) {
if ($inputVal > 50) {
$inputVal = 2;
}
}
修改后:
/**
* 打折
* @param $inputVal
* @param $quantity
* @param $yearToDate
*/
public function discount ($inputVal, $quantity, $yearToDate) {
$result = $inputVal;
if ($result > 50) {
$result = 2;
}
}
动机
- 如果参数$foo是一个对象,那么对参数赋值意味着改变$foo所引用的对象.
- 这样做会降低代码的清晰度.
做法
- 建立一个临时变量,把待处理的参数值赋予它
- 已对参数的赋值为界, 将其后所有对此参数的引用点,全部替换为对此临时变量的引用
- 修改赋值语句,时期改为对新建之临时变量赋值
网友评论