当代码流是这样的:

if(check())
{
  ...
  ...
  if(check())
  {
    ...
    ...
    if(check())
    {
      ...
      ...
    }
  }
}

我通常看到这种方法可以避免上述混乱的代码流:

do {
    if(!check()) break;
    ...
    ...
    if(!check()) break;
    ...
    ...
    if(!check()) break;
    ...
    ...
} while(0);

有什么更好的方法可以避免这种工作/黑客,从而使其成为更高级别(行业级别)的代码?

任何跳出盒子的建议都是欢迎的!


当前回答

我不是c++程序员,所以我不会在这里写任何代码,但到目前为止还没有人提到面向对象的解决方案。下面是我的猜测:

拥有一个通用接口,该接口提供了一个方法来评估单个条件。现在,您可以在包含有问题的方法的对象中使用这些条件的实现列表。遍历列表并计算每个条件,如果其中一个条件失败,可能会提前爆发。

这样的设计很好地遵循了开/闭原则,因为在初始化包含相关方法的对象时,可以很容易地添加新的条件。您甚至可以向接口添加第二个方法,该方法用于条件评估,返回条件的描述。这可以用于自文档系统。

但是,缺点是由于使用了更多的对象和遍历列表,所涉及的开销稍微多一些。

其他回答

类似于dasblinkenlight的答案,但避免了if语句中的赋值,这可能会被代码评审员“修复”:

bool goOn = check0();
if (goOn) {
    ...
    goOn = check1();
}
if (goOn) {
    ...
    goOn = check2();
}
if (goOn) {
    ...
}

...

当一个步骤的结果需要在下一步之前检查时,我使用这种模式,这与所有检查都可以在前面用一个大if(check1() && check2()…类型的模式。

你可以使用一个简单的bool变量的延续模式:

bool goOn;
if ((goOn = check0())) {
    ...
}
if (goOn && (goOn = check1())) {
    ...
}
if (goOn && (goOn = check2())) {
    ...
}
if (goOn && (goOn = check3())) {
    ...
}

这个执行链将在checkN返回false时停止。由于&&操作符短路,将不再执行进一步的检查…()调用。此外,优化编译器足够聪明,可以识别将goOn设置为false是单行道,并为您插入缺少的goto结尾。因此,上面代码的性能将与do/while(0)相同,只是对其可读性没有严重的影响。

I'm adding an answer for the sake of completeness. A number of other answers pointed out that the large condition block could be split out into a separate function. But as was also pointed out a number of times is that this approach separates the conditional code from the original context. This is one reason that lambdas were added to the language in C++11. Using lambdas was suggested by others but no explicit sample was provided. I've put one in this answer. What strikes me is that it feels very similar to the do { } while(0) approach in many ways - and maybe that means it's still a goto in disguise....

earlier operations
...
[&]()->void {

    if (!check()) return;
    ...
    ...
    if (!check()) return;
    ...
    ...
    if (!check()) return;
    ...
    ...
}();
later operations

我就是这么做的。

void func() {
  if (!check()) return;
  ...
  ...

  if (!check()) return;
  ...
  ...

  if (!check()) return;
  ...
  ...
}

为什么标记法没有被回答,这是自古以来使用的方法。

//you can use something like this (pseudocode)
long var = 0;
if(condition)  flag a bit in var
if(condition)  flag another bit in var
if(condition)  flag another bit in var
............
if(var == certain number) {
Do the required task
}