我现在遇到过几次这种情况,我会有一个看起来像这样的逻辑结构。
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
}
每种情况下的结构都是相同的,唯一的区别是被调用的函数。但是现在我正在重复我的逻辑,那只是感觉很脏。我觉得有一种更优雅的方式来处理这些情况,但我还没遇到过。
关于如何重构这个的任何想法?
编辑:稍微改变了示例的结构以更多地强调问题。
答案 0 :(得分:0)
我不确定,但我很想尝试这样:
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"