gpt4 book ai didi

refactoring - 如何简化复杂的业务 "IF"逻辑?

转载 作者:行者123 更新时间:2023-12-03 21:17:30 28 4
gpt4 key购买 nike

处理乍一看需要许多嵌套 if 语句的复杂业务逻辑的好方法是什么?

例子:

折扣券。可能:

1a) 超值折扣
1b) 百分比折扣

2a) 正常折扣
2b) 累进折扣

3a) 需要访问优惠券
3b) 不需要访问优惠券

4a) 仅适用于之前已经购买的客户
4b) 适用于任何客户

5a) 仅适用于来自国家(X、Y、...)的客户

这需要更复杂的代码:

if (discount.isPercentage) {
if (discount.isNormal) {
if (discount.requiresAccessCoupon) {
} else {
}
} else if (discount.isProgressive) {
if (discount.requiresAccessCoupon) {
} else {
}
}
} else if (discount.isValue) {
if (discount.isNormal) {
if (discount.requiresAccessCoupon) {
} else {
}
} else if (discount.isProgressive) {
if (discount.requiresAccessCoupon) {
} else {
}
}
} else if (discount.isXXX) {
if (discount.isNormal) {
} else if (discount.isProgressive) {
}
}

即使您将 IF 替换为 switch/case,它仍然太复杂了。
有什么方法可以使它可读、可维护、更可测试和易于理解?

最佳答案

好问题。 “条件复杂性”是一种代码味道。 Polymorphism是你的 friend 。

Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a few lines of code. Unfortunately, it rarely ages well. You implement several new features and suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]



避免嵌套 if 块可以做的最简单的事情之一就是学会使用 Guard Clauses .
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};

我发现的另一件事可以很好地简化事情,并使您的代码自我记录,是 Consolidating conditionals .
double disabilityAmount() {
if (isNotEligableForDisability()) return 0;
// compute the disability amount

其他贵重 refactoring与条件表达式相关的技术包括 Decompose Conditional , Replace Conditional with Visitor , 和 Reverse Conditional .

关于refactoring - 如何简化复杂的业务 "IF"逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1607252/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com