美文网首页
重新组织函数-Remove Assignments to Par

重新组织函数-Remove Assignments to Par

作者: 瑾然有昫 | 来源:发表于2019-12-18 17:59 被阅读0次

代码对一个参数进行赋值.以一个临时变量取代该参数的位置

示例:

修改前:

    /**
     * 打折
     * @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;
        }
    }

动机

  1. 如果参数$foo是一个对象,那么对参数赋值意味着改变$foo所引用的对象.
  2. 这样做会降低代码的清晰度.

做法

  1. 建立一个临时变量,把待处理的参数值赋予它
  2. 已对参数的赋值为界, 将其后所有对此参数的引用点,全部替换为对此临时变量的引用
  3. 修改赋值语句,时期改为对新建之临时变量赋值

相关文章

网友评论

      本文标题:重新组织函数-Remove Assignments to Par

      本文链接:https://www.haomeiwen.com/subject/ktbunctx.html