If statement 嵌套If语句中的重复逻辑
我已经遇到过这种情况好几次了,我会有一个类似这样的逻辑结构If statement 嵌套If语句中的重复逻辑,if-statement,logic,structure,If Statement,Logic,Structure,我已经遇到过这种情况好几次了,我会有一个类似这样的逻辑结构 switch(someInteger) { case 1: if(conditionA) { if(conditionB) { func1(); } else { func2(); } } else { func3();
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"
那当然更干净了,尽管结构还是一样。问题是,如果某个整数有12个不同的值,我也想应用这个逻辑,那么我的手上就会有一堆乱七八糟的东西。添加大量其他值肯定会使
else if
语句的列表变长。但结构保持不变,您可以轻松地向下扫描列表以查找任何特定条件。所以我不会认为这是一个“烂摊子”——它给出了一个清晰且可重复的结构,它可以在必要时进行缩放。