2

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

 2 years ago
source link: https://juejin.cn/post/7083313964041371679
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

2022年04月06日 02:37 ·  阅读 10

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

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

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

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

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

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

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);
}
复制代码

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

文章被收录于专栏:
cover
程序员之家
技术资讯分享,欢迎投稿、交流~
安装掘金浏览器插件
多内容聚合浏览、多引擎快捷搜索、多工具便捷提效、多模式随心畅享,你想要的,这里都有!
前往安装

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK