嵌套冗余“如果”条件 [英] Nested redundant 'if' conditions
本文介绍了嵌套冗余“如果”条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有更好的(或清洁剂)的方式来编写以下code?
Is there a better (or cleaner) way to write the following code?
if(conditionX)
{
if(condition1)
{
// code X1
}
else if(condition2)
{
// code X2
}
}
else if(conditionY)
{
if(condition1)
{
// code Y1
}
else if(condition2)
{
// code Y2
}
}
我有一些更多的条件,但我想你明白了吧。
I have a few more conditions, but I guess you get the point.
推荐答案
有四种方法解决这个问题,其中没有一个是普遍的:
There are four approaches to this problem, none of which is universal:
- 发表的一切,是 - 没有太多code在这里重复。如果计算
条件1
和条件2
是棘手的,计算它们的前期并将它们保存在BOOL
变量 - 请
conditionX
和conditionY
产生一个结果,让您统一条件1
和条件2
- 这并不总是可能的,但在某些情况下,你可以prepare来统一所采取的活动的变量在两个分支,比方说,使用函数指针或一个lambda。 - 把处理逻辑与虚函数的子类,以消除条件逻辑 - 这是可能的,只有当你的初始设计错失机会的子类。从本质上讲,这种方法推动上
conditionX决定
/conditionY
成在其中创建一个子类的地方,然后在重复使用后来那个决定通过调用接口的虚拟函数的一个适当的替代。 - 创建重新presenting所有这三个条件的数值组合,并转换为
开关
- 此招统一的条件语句,减少嵌套
- Leave everything as is - There isn't much code duplication here. If computing
condition1
andcondition2
is tricky, compute them upfront and store them inbool
variables - Make
conditionX
andconditionY
produce a result that lets you unifycondition1
andcondition2
- This is not always possible, but in some situations you could prepare a variable that unifies the activities taken in the two branches, say, by using a function pointer or a lambda. - Put the processing logic into subclasses with virtual functions to eliminate conditional logic - This is possible only when your initial design missed an opportunity to subclass. Essentially, this approach pushes the decision on
conditionX
/conditionY
into a place where a subclass is created, and then "reuses" that decision later on by calling a proper override of a virtual function in the interface. - Create a numeric combination representing all three conditions, and convert to
switch
- This trick unifies the conditionals, reducing the nesting.
下面是最后方法的一个例子:
Here is an example of the last approach:
int caseNumber = ((conditionX?1:0) << 3)
| ((conditionY?1:0) << 2)
| ((condition2?1:0) << 1)
| ((condition1?1:0) << 0);
switch (caseNumber) {
case 0x09:
case 0x0D:
case 0x0F: // code X1
break;
case 0x0A:
case 0x0E: // code X2
break;
case 0x05:
case 0x07: // code Y1
break;
case 0x06: // code Y2
break;
}
这篇关于嵌套冗余“如果”条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文