如何避免"若"链? [英] How to avoid "if" chains?
问题描述
假设我有这样的伪code:
Assuming I have this pseudo-code:
bool conditionA = executeStepA();
if (conditionA){
bool conditionB = executeStepB();
if (conditionB){
bool conditionC = executeStepC();
if (conditionC){
...
}
}
}
executeThisFunctionInAnyCase();
功能 executeStepX
应当且仅当在previous成功执行。
在任何情况下, executeThisFunctionInAnyCase
函数应该在年底被调用。
我在编程的新手,对于非常基本的问题,很抱歉:有没有办法(在C / C ++为例),以避免长如果
链产生那种code的金字塔,在code易读性为代价?
Functions executeStepX
should be executed if and only if the previous succeed.
In any case, the executeThisFunctionInAnyCase
function should be called at the end.
I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if
chain producing that sort of "pyramid of code", at the expense of the code legibility?
我知道,如果我们能跳过 executeThisFunctionInAnyCase
函数调用时,code可以简化为:
I know that if we could skip the executeThisFunctionInAnyCase
function call, the code could be simplified as:
bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;
但限制是 executeThisFunctionInAnyCase
函数调用。
可以在破
语句以某种方式使用吗?
But the constraint is the executeThisFunctionInAnyCase
function call.
Could the break
statement be used in some way?
推荐答案
您可以使用&放大器;&安培;
(逻辑与):
You can use an &&
(logic AND):
if (executeStepA() && executeStepB() && executeStepC()){
...
}
executeThisFunctionInAnyCase();
这将满足您的两个要求:
this will satisfy both of your requirements:
-
executeStep< X>()
应评估只有previous 1成功(这就是所谓的 短路评价的) -
executeThisFunctionInAnyCase()
将在任何情况下要执行
executeStep<X>()
should evaluate only if the previous one succeeded (this is called short circuit evaluation)executeThisFunctionInAnyCase()
will be executed in any case
这篇关于如何避免&QUOT;若&QUOT;链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!