“滥用”循环以减少嵌套 [英] "Abusing" loops for reducing if-nesting

查看:118
本文介绍了“滥用”循环以减少嵌套的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候必须实现一系列的if / else检查。

Sometime one have to implement a series of if/else checks. In old-days goto was the sandard instrument for this.

由于goto在许多代码风格指南中都是不允许的,所以我有时使用循环作为替换,例如: / p>

As goto is a no-go in many code style guides, I sometimes use loops as a replacement e.g.:

do
{
  if (a)
  {
   doA();
   break;
  }
  //...
  if (z)
  {
   doZ();
   break;
  }
}while(false);

//all break jump here

这是一个好方法吗?有没有一个好的C ++模式(例如使用模板,继承等)来实现这个没有太多的开销?

Is it a good approach? Is there a good C++ pattern (e.g. using templates, inheritance, etc.) for implementing this without too much overhead?

推荐答案

一般用于编写可维护代码,你应该按照他们的意图使用语言的工具。
你使用的循环应该只循环一次迭代显然是一个偏向不是一套相同的代码风格指南,皱眉 goto

In general for writing maintainable code you should use the tools of the language in the way they are intended. Your usage of a loop that is supposed to only loop for one iteration is clearly a deflection not intended by the very same set of code style guidelines that frown upon goto in the first place.

语言中提供了一些工具,使您更容易与其他程序员沟通,并进一步自我你想在这里做什么。

There are some tools available in the language that make it easier for you to communicate to other programmers and your further self what you are intending to do here.


  • 其中之一是将此代码块外包到一个单独的方法中,并使用 return 语句。

  • 另一个解决方案可能是使用异常,你可以尝试/ catch。它是否符合你的目的主要取决于你正在做的检查的种类。

  • 最后,if / else链可能看起来不是很优雅,但另一方面是一个结构这留下了很少的误解空间。

  • One of them is to outsource this code block into a separate method and use the return statement. Funny enough early returns are also frowned upon by some.
  • Another solution could be the use of exceptions, where you try/catch. Whether it fits your purpose mostly depends on the kind of "checks" you are doing.
  • Finally, a chain of if/else might not look very elegant but on the other hand is a construct that leaves few room for misinterpretation.

这篇关于“滥用”循环以减少嵌套的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆