构造是否做.. while(false)有助于更好的控制流? [英] Does the construct do .. while(false) contribute to better control flow?

查看:85
本文介绍了构造是否做.. while(false)有助于更好的控制流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近遇到了以下代码:

I've recently come across this code:

do {
    if ( ! checkSomething() )
        break;

    // some code

    if ( ! checkSomeOtherThing() )
        break;

    // some other code
} while(false);

// some final code

编写它的程序员按照"cleaner control flow"的方式写了一条注释.

The programmer that wrote it, wrote a comment along the lines of "cleaner control flow".

在我看来,如果将原始代码重构为其他代码,则原始代码看起来可能会更好.但是这句话有什么道理吗?这个构造好吗?

In my opinion, the original code could look better if its refactored into something else. But is there any truth in this statement ? Is this construct any good ?

推荐答案

如果您不介意包含多个break语句的循环,那么这里唯一的问题是C(出于明显的原因)不允许您中断因此,一些毫无戒心的未来维护者可能会误认为是真正的循环.

If you don't mind loops containing several break statements, then the only problem here is that C (for obvious reasons) doesn't let you break out of a bare block, hence the "non-loop" which some unsuspecting future maintainer could mistake for a real loop.

我认为考虑因素是:

  • 如果只有两个break点,那么两个if语句有什么不好呢?
  • 如果有两个以上的断点,则使用if语句的缩进可能会令人不快,这样可以节省下来,但是函数又做得太多了吗?即使不是,最好还是使用goto并避免不循环的怪异循环?
  • if there are only two break points, what's so bad about two if statements?
  • if there are more than two break points then the indentation with if statements could get unpleasant, and this saves that, but then again is the function doing too much? And even if not, would it be better just to use goto and avoid the weirdness of a loop that doesn't loop?

由于您标记了不可知的语言,因此我曾经使用宏化的汇编语言,并带有block ... endblock可能会打破.这导致了用于检查必要条件的相当不错的代码,例如:

Since you tag this language-agnostic, I used to use a macroised assembly language, with a block ... endblock that you could break out of. This lead to reasonably nice code for checking necessary conditions, such as:

block
    breakif str1 == null
    breakif str2 == null
    get some combined property of str1 and str2
    breakif some other condition that stops us getting on with it
    get on with it
endblock

实际上,它不是breakif str1 == null,不是breakifeq.p str1, null或类似的东西,但我确切地忘记了什么.

Actually, it wasn't breakif str1 == null, it was breakifeq.p str1, null, or something like that, but I forget exactly what.

这篇关于构造是否做.. while(false)有助于更好的控制流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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