嵌套 If 语句中的重复逻辑

马克斯·利明

我已经遇到过几次这种情况,在那里我将有一个看起来像这样的逻辑结构。

switch(someInteger) 
{
    case 1:
        if(conditionA) {
            if(conditionB) {
                 func1();
            } else {
                 func2();
            }
        } else {
            func3();
        }
        break;

    case 2:
        if(conditionA) {
            if(conditionB) {
                 func4();
            } else {
                 func5();
            }
        } else {
            func6();
        }
        break;
    case 2:
        //ditto
    case 3:
        //ditto
    case someObnoxiouslyHighNumber:
        //ditto
}

每种情况下的结构都是相同的,唯一的区别是被调用的函数。但是现在我正在复制我的逻辑,这感觉很脏。我觉得有一种更优雅的方法来处理这些情况,但我还没有遇到过。

关于如何重构这个的任何想法?

编辑:稍微改变了示例的结构以更加强调问题。

马特克拉克

我不确定,但我很想以这种方式尝试:

if      someInteger == 1 and conditionA and conditionB  then func1
else if someInteger == 1 and conditionA and !conditionB then func2
else if someInteger == 1 and !conditionA                then func3
else if someInteger == 2 and conditionA and conditionB  then func4
else if someInteger == 2 and conditionA and !conditionB then func5
else if someInteger == 2 and !conditionA                then func6
else error "Uncharted territory"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章