循环中的条件,最佳实践?

Jos*_*osh 9 c++ java loops coding-style

说我有这样的循环:

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
        continue;
    }
    doSomeOtherStuff();
}
Run Code Online (Sandbox Code Playgroud)

与...

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
    }
    else
    {
        doSomeOtherStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

有没有理由使用一个而不是另一个?或者只是个人偏好?
我要求的主要语言是Java,但我想它也适用于大多数其他语言.

Mic*_*ker 16

从技术上讲,不,但我发现第二个更适合这个特殊情况.


par*_*mar 7

我更喜欢第二种结构......

for (int i = 0; i < someint; i++)
{
    if (i == somecondition)
    {
        DoSomething();
        //lets say lot of code
        //..
        //...
        //...
        //...
        continue;
    }
    else
    {
        doSomeOtherStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

让我们说你之前有很多代码continue.通过观察,它立即显而易见

   else
    {
        doSomeOtherStuff();
    }
Run Code Online (Sandbox Code Playgroud)

它没有无条件执行.

  • +1:在已经删除的答案中,具有40k +声望点的成员错过了`continue`声明.我认为这是一个非常强大的指标,即使有相对较短的if/else语句,有经验的程序员仍然可以错过它.else块使这一点更清晰. (3认同)

das*_*ght 5

对我来说,这取决于分支thenelse分支相对大小之间的分歧:如果一个大于另一个,而较小的一个代表逻辑上的异常情况,我将较短的一个放入then,并添加一个continue; 当他们大致相等,无论在规模和逻辑流,我让他们在自己thenelse分支机构.

for (String tok : tokens) {
    if (isKeyword(tok)) {
         output.write(tok);
         continue;
    }
    // Do some massive processing of non-keyword tokens here
    // This block goes on...
    // and on...
    // and on... You get the idea
}
Run Code Online (Sandbox Code Playgroud)

for (String op : operators) {
    if (isAdditive(op)) {
        // Do something for additive ops
    } else {
        // Do something for non-additive ops
    }
}
Run Code Online (Sandbox Code Playgroud)