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

    临时变量的问题在于:

    它们是暂时的,而且只能在所属函数内使用。由于临时变量只在所属函数内可见,所以,如果很多地方都在用这个临时变量,就会驱使你写出更长的函数。如果把临时变量替换为一个查询,那么其他函数中都可以获得这份信息。

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

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

    示例:

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

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

    1、把赋值动作的右侧表达式提炼出来

    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;
    }

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

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

    3、用类似的办法,提炼另外一个临时变量

    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作为参数。

    个人感悟:

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

  • 相关阅读:
    方法重载与方法重写的概念和区别(转载)
    sql exist 和not exist(转载)
    SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思 sql server 2005 2008
    sql中的isnull
    sql中unique和distinct
    SQLServer中的Merge使用
    SQL Server系统表sysobjects介绍与使用
    sql select as
    存储过程SET XACT_ABORT ON
    SQL Server之存储过程基础知识
  • 原文地址:https://www.cnblogs.com/happypayne/p/8384477.html
Copyright © 2011-2022 走看看