当代码流是这样的:

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

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

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

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

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


当前回答

如果你的代码有一个很长的If ..else If ..else语句块,你可以尝试在函子或函数指针的帮助下重写整个块。这可能并不总是正确的解决方案,但通常是正确的。

http://www.cprogramming.com/tutorial/functors-function-objects-in-c++.html

其他回答

有些时候,使用goto实际上是正确的答案——至少对那些没有在宗教信仰中长大的人来说,“不管问题是什么,goto永远都不是答案”——这是其中的一个例子。

此代码使用了do{…}, (0);唯一的目的就是把一个傻瓜打扮成休息的样子。如果你打算使用goto,那就公开使用它。让代码更难阅读是没有意义的。

一种特殊的情况是当你有很多代码和相当复杂的条件时:

void func()
{
   setup of lots of stuff
   ...
   if (condition)
   {
      ... 
      ...
      if (!other condition)
      {
          ...
          if (another condition)
          {
              ... 
              if (yet another condition)
              {
                  ...
                  if (...)
                     ... 
              }
          }
      }
  .... 

  }
  finish up. 
}

没有如此复杂的逻辑,实际上可以更清楚地表明代码是正确的。

void func()
{
   setup of lots of stuff
   ...
   if (!condition)
   {
      goto finish;
   }
   ... 
   ...
   if (other condition)
   {
      goto finish;
   }
   ...
   if (!another condition)
   {
      goto finish;
   }
   ... 
   if (!yet another condition)
   {
      goto finish;
   }
   ... 
   .... 
   if (...)
         ...    // No need to use goto here. 
 finish:
   finish up. 
}

编辑:澄清一下,我绝不是建议使用goto作为通用解决方案。但在某些情况下,goto是比其他解决方案更好的解决方案。

例如,想象一下,我们正在收集一些数据,测试的不同条件是某种“这是正在收集的数据的结束”——这取决于某种“继续/结束”标记,这些标记根据您在数据流中的位置而变化。

现在,当我们完成之后,我们需要将数据保存到一个文件中。

是的,通常有其他解决方案可以提供合理的解决方案,但并不总是如此。

我就是这么做的。

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

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

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

使用异常。您的代码将看起来更加清晰(并且创建异常正是为了处理程序执行流中的错误)。有关清理资源(文件描述符,数据库连接等),请阅读文章“为什么c++不提供一个“finally”结构?”

#include <iostream>
#include <stdexcept>   // For exception, runtime_error, out_of_range

int main () {
    try {
        if (!condition)
            throw std::runtime_error("nope.");
        ...
        if (!other condition)
            throw std::runtime_error("nope again.");
        ...
        if (!another condition)
            throw std::runtime_error("told you.");
        ...
        if (!yet another condition)
            throw std::runtime_error("OK, just forget it...");
    }
    catch (std::runtime_error &e) {
        std::cout << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught an unknown exception\n";
    }
    return 0;
}

如果根据故障发生的位置需要不同的清理步骤,另一个模式很有用:

    private ResultCode DoEverything()
    {
        ResultCode processResult = ResultCode.FAILURE;
        if (DoStep1() != ResultCode.SUCCESSFUL)
        {
            Step1FailureCleanup();
        }
        else if (DoStep2() != ResultCode.SUCCESSFUL)
        {
            Step2FailureCleanup();
            processResult = ResultCode.SPECIFIC_FAILURE;
        }
        else if (DoStep3() != ResultCode.SUCCESSFUL)
        {
            Step3FailureCleanup();
        }
        ...
        else
        {
            processResult = ResultCode.SUCCESSFUL;
        }
        return processResult;
    }

在函数中隔离这些决策并使用返回而不是中断被认为是可以接受的实践。虽然所有这些检查都对应于与函数相同的抽象级别,但这是一种非常符合逻辑的方法。

例如:

void foo(...)
{
   if (!condition)
   {
      return;
   }
   ...
   if (!other condition)
   {
      return;
   }
   ...
   if (!another condition)
   {
      return;
   }
   ... 
   if (!yet another condition)
   {
      return;
   }
   ...
   // Some unconditional stuff       
}