zoukankan      html  css  js  c++  java
  • 【重构】重新组织函数

    一、重新组织函数

    1.1、Extract Method (提炼函数)

    befor:

    void pringOwing(double amount){
    
        printBanner();
    
        //print detail
        System.out.println("name:"+_name);
        System.out.println("amount:"+amount);
    }
    

    after:

    void pringOwing(double amount){
        printBanner();
        printDetails(amount);
    }
    
    void printDetails(double amount){
        System.out.println("name:"+_name);
        System.out.println("amount:"+amount);
    }
    

    1.2、Inline Method(内联函数)

    before:

    void getRating(){
        return (moreThanFiveLateDeliveries()) ? 2 : 1;
    }
    
    boolean moreThanFiveLateDeliveries(){
        return _numberOfLateDeliveries > 5;
    }
    

    after:

    void getRating(){
        return (_numberOfLateDeliveries > 5) ? 2 : 1;
    }
    
    

    1.3、Inline Temp (内联临时变量)

    before:

    double basePrice = anOrder.basePrice();
    return (basePrice>1000);
    

    after:

    return (anOrder.basePrice()>1000);
    

    1.4、Replace Temp With Query (以查询代替临时变量)

    before:

    double basePrice = _quantity * _itemPrice;
    if (basePrice > 1000) 
        return  basePrice * 0.95;
    else
        return  basePrice * 0.98;
    

    after:

    if (basePrice() > 1000) 
        return  basePrice() * 0.95;
    else
        return  basePrice() * 0.98;
    
    
    double basePrice(){
        return  _quantity * _itemPrice;
    }
    
    

    1.5、Introduce Explaining Variable (引入解释性变量)

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

    after:

    boolean isMacOs = platorm.toUpperCase().indexOf("MAC")>-1;
    boolean isIEBrowers = platorm.toUpperCase().indexOf("IE")>-1;
    boolean wasResize = resize > 0;
    
    if (isMacOs && isIEBrowers && wasInitialized() && wasResize){
        //do something
    }
    
    “年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
  • 相关阅读:
    使用mt_rand代替rand
    array_diff 不注意的坑
    stackoverflow 技术问答社区
    js检查浏览器是否处于隐身模式
    api数据接口
    图像识别api
    ionic creator(ionic生成器)
    商城金币设计
    details和summary标签
    iOS多线程编程之NSOperation的基本操作
  • 原文地址:https://www.cnblogs.com/jzsg/p/10822866.html
Copyright © 2011-2022 走看看