• 实例带你掌握如何分解条件表达式


    摘要:大型函数本身就会降低代码可读性,而条件逻辑则会使代码更难阅读。

    本文分享自华为云社区《分解条件表达式(Decompose Conditional)》,作者: JavaEdge 。

    1 动机

    程序中复杂的条件逻辑导致我必须编写代码来检查不同的条件分支,根据不同条件做不同的事,然后,我很快就会得到一个相当长的函数。大型函数本身就会降低代码可读性,而条件逻辑则会使代码更难阅读。

    带有复杂条件逻辑的函数中,代码(包括检查条件分支的代码和真正实现功能的代码)会告诉我发生的事,但常常让我弄不清楚为什么会发生这样的事, 说明代码可读性的确大大降低。

    和任何大块头代码一样,我可以将它分解为多个独立的函数,根据每个小块代码的用途,命名分解而得的新函数,并将原函数中对应的代码改为调用新函数,从而更清楚表达意图。

    对于条件逻辑,将每个分支条件分解成新函数还能带来更多好处:可突出条件逻辑,更清楚地表明每个分支的作用,并且突出每个分支的原因。 本重构手法其实只是【提炼函数】的一个应用场景。但我要强调该场景,因为我发现它经常会带来很大价值。

    2 做法

    对条件判断和每个条件分支分别运用【提炼函数】手法。

    3 案例

    假设我要计算购买某样商品的总价(总价=数量×单价),而这个商品在冬季和夏季的单价不同:

    public static void price(LocalDate aDate, Plan plan, Long quantity) {
      if (!aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd)) {
        charge = quantity * plan.summerRate;
      } else {
        charge = quantity * plan.regularRate + plan.regularServiceCharge;
      }
    }

    将条件判断提炼到一个独立方法:

       /**
         * 在冬季和夏季的单价不同
         */
        public static void price(LocalDate aDate, Plan plan, Long quantity) {
            if (summer(aDate, plan)) {
                charge = quantity * plan.summerRate;
            } else {
                charge = quantity * plan.regularRate + plan.regularServiceCharge;
            }
        }
    
        public static boolean summer(LocalDate aDate, Plan plan) {
            return !aDate.isBefore(plan.summerStart) && !aDate.isAfter(plan.summerEnd);
        }

    然后提炼条件判断为真的分支:

    /**
     * 在冬季和夏季的单价不同
     */
    public static void price(LocalDate aDate, Plan plan, Long quantity) {
      if (summer(aDate, plan)) {
        charge = summerCharge(plan, quantity);
      } else {
        charge = quantity * plan.regularRate + plan.regularServiceCharge;
      }
    }
    
    /**
     * 提炼条件判断为真的分支
     */
    public static Long summerCharge(Plan plan, Long quantity) {
      return quantity * plan.summerRate;
    }
    }

    最后提炼条件判断为假的分支:

    /**
     * 在冬季和夏季的单价不同
     */
    public static void price(LocalDate aDate, Plan plan, Long quantity) {
      if (summer(aDate, plan)) {
        charge = summerCharge(plan, quantity);
      } else {
        charge = regularCharge(plan, quantity);
      }
    }
    
    private static Long regularCharge(Plan plan, Long quantity) {
      return quantity * plan.regularRate + plan.regularServiceCharge;
    }

    提炼完成后,我喜欢用三元运算符重新安排条件语句。

    /**
     * 在冬季和夏季的单价不同
     */
    public static void price(LocalDate aDate, Plan plan, Long quantity) {
      charge = summer(aDate, plan) ? summerCharge(plan, quantity) : regularCharge(plan, quantity);
    }

     

    点击关注,第一时间了解华为云新鲜技术~

  • 相关阅读:
    JS防止刷新,后退,关闭
    IIS日志-网站运维的好帮手
    未能加载文件或程序集“XXX”或它的某一个依赖项。磁盘空间不足---解决方案
    NOPI导出标准格式Excel
    DRBD+Heartbeat+Mysql高可用环境部署
    LVS三种包转发模型调度算法
    nagios环境部署(rhel6.5)
    关于nagios监控
    关于memcached原理及安装部署
    PHP5.4.36 RHEL6.5 源码编译安装
  • 原文地址:https://www.cnblogs.com/huaweiyun/p/16105596.html
Copyright © 2020-2023  润新知