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. 马尔克斯
  • 相关阅读:
    Python基础 面向对象的基本概念
    C#版菜谱
    Ember源码学习
    AutoFac文档
    NewLife.Xcode组件资源目录
    Go语言
    调试Razor从哪里开始
    搭建一个高并发低时延系统
    ASP.NET MVC以ModelValidator为核心的Model验证体系: ModelValidatorProvider
    2012百度之星资格赛试题与AC代码合集
  • 原文地址:https://www.cnblogs.com/jzsg/p/10822866.html
Copyright © 2011-2022 走看看