美文网首页
重构读书笔记-6_4-Introduce Explaining

重构读书笔记-6_4-Introduce Explaining

作者: MR_Model | 来源:发表于2019-06-10 09:45 被阅读0次

    重构第六章

    5.Introduce Explaining Variable(引入解释变量)

    将该复杂表达式的结果放进临时变量,以此变量名称来解释表达式用途

    动机:

    1、条件逻辑语句中,将每个子句提炼出来,以一个良好的命名来解释对应子句的含义
    2、较长算法中可以用临时变量解释每一步的意义
    

    你有一个复杂的表达式

    Example:

    if ((platform.toUpperCase().indexOf("MAC") >-1 )&&
    (browser.toUpperCase().indexOf("IE") > -1) &&
    wasInitialized()&& resize >0) {
        // do something
    }
    

    Analyse:

    Introduce Explaining Variable(引入解释变量)和Extract Method(提炼函数) 的区别是一个借助了临时变量,另一个将代码块封装成为了另外的函数。
    书中作者推荐使用Extract Method(提炼函数) 进行代码的重构,因为Introduce Explaining Variable(引入解释变量)本质是添加了临时变量,而临时变量有它自身的局限性。
    
    书中使用Introduce Explaining Variable(引入解释变量)的时机是在Extract Method(提炼函数)代码工作量巨大的时候而使用的,同时下一步再使用Replace Temp With Query(查询取代变量)将引用的解释性临时变量去掉
    

    End:

    final boolean isMacOS = platform.toUpperCase().indexOf("MAC") >-1;
    final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1;
    final boolean wasResized = resize >0;
    if (isMacOS && isIEBrowser && wasInitialized() && wasResized) {
        // do something
    }
    

    Conclusion:

    Introduce Explaining Variable(引入解释变量)是一个很适用于重构过程中的方法,他可以使得代码逻辑更加的清晰,使得编程人员阅读的更加顺畅,但同时如果他引入了过多的临时变量,可能会使得程序部分功能显得有些臃肿,所以需要和其他的重构方法配合使用才能使得程序的结构更加的清晰,可复用性更加的好
    

    示例:

    int chineseResult =QueryChineseResult(pClass->pTeacher->pStudent->ID);
    int mathResult = QueryChineseResult(pClass->pTeacher->pStudent->ID);
    int totalPoint = QueryTatolPoint(pClass->pTeacher->pStudent->ID);
    std::cout<<"This student ID is "<<pClass->pTeacher->pStudent->ID<<", chinese Result is "<<chineseResult<<",math Result is "<<mathResult<<"total point is" << totalPoint <<"."<<std::endl;
    

    引入解释变量之后:

    int stuID = pClass->pTeacher->pStudent->ID;
    int chineseResult =QueryChineseResult(stuID);
    int mathResult = QueryChineseResult(stuID);
    int totalPoint = QueryTatolPoint(stuID);
    std::cout<<"This student ID is "<<stuID<<", chinese Result is "<<chineseResult<<",math Result is "<<mathResult<<"total point is" << totalPoint <<"."<<std::endl;
    

    使用Introduce Explaining Variable(引入解释变量)可以使得程序小范围内的代码阅读起来更加的流畅、通顺。

    相关文章

      网友评论

          本文标题:重构读书笔记-6_4-Introduce Explaining

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