如何简化复杂的业务“IF"逻辑? [英] How to simplify complicated business "IF" logic?

查看:73
本文介绍了如何简化复杂的业务“IF"逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What are the good ways to handle complicated business logic that from the first glance requires many nested if statements?

示例:

折扣券.可能是:

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

1a) Value discount
1b) Percentage discount

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

2a) Normal discount
2b) Progressive discount

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

3a) Requires access coupon
3b) Do not require access coupon

4a) 只适用于已经购买过的客户
4b) 适用于任何客户

4a) Applied only to the customer who already bought before
4b) Applied to any customer

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

5a) Applied to customer only from countries (X,Y,…)

这需要比这个更复杂的代码:

That requires code even more complicated then this:

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,它仍然太复杂了.有哪些方法可以使其可读、可维护、更可测试且易于理解?

Even if you replace IFs to switch/case it's still too complicated. What are the ways to make it readable, maintainable, more testable and easy to understand?

推荐答案

我会编写一个通用的状态机,以要比较的事物列表为基础.

I would write a generic state-machine that feeds on lists of things to compare.

这篇关于如何简化复杂的业务“IF"逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆