切换不间断 [英] Switch without break

查看:88
本文介绍了切换不间断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些switch语句,如下所示。请注意,没有休息。
Findbugs仅在第二个案例陈述中报告错误。
错误是:在一个案例落到下一个案例的地方找到Switch语句。

I have some switch statement as shown below. Notice there is no break. Findbugs is reporting error on the second case statement only. The error is : Switch statement found where one case falls through to the next case.

switch(x) {

    case 0:
        // code

    case 1:
        // code

    case 2:
        // code
}


推荐答案

Findbugs是如果在第一个代码中有任何代码(尽管有时候它可以用来产生良好的效果),那么从一个 case 下降到下一个通常不是一个好主意。因此,当它看到第二个案例并且没有中断时,它会报告错误。

Findbugs is flagging up that falling through from one case to the next is generally not a good idea if there's any code in the first one (although sometimes it can be used to good effect). So when it sees the second case and no break, it reports the error.

例如:

switch (foo) {
    case 0:
        doSomething();
    case 1:
        doSomethingElse();
    default:
        doSomeOtherThing();
}

这是完全有效的Java,但它可能不会做作者预期:如果 foo 0 所有三个函数 doSomething doSomethingElse doSomeOtherThing 运行(按此顺序)。如果 foo 1 ,则只有 doSomethingElse doSomeOtherThing 运行。如果 foo 是任何其他值,则仅运行 doSomeOtherThing

This is perfectly valid Java, but it probably doesn't do what the author intended: If foo is 0, all three of the functions doSomething, doSomethingElse, and doSomeOtherThing run (in that order). If foo is 1, only doSomethingElse and doSomeOtherThing run. If foo is any other value, only doSomeOtherThing runs.

相比之下:

switch (foo) {
    case 0:
        doSomething();
        break;
    case 1:
        doSomethingElse();
        break;
    default:
        doSomeOtherThing();
        break;
}

此处,只会运行其中一个函数,具体取决于<的值code> foo 。

Here, only one of the functions will run, depending on the value of foo.

因为忘记休息,像Findbugs这样的工具会为你标记它。

Since it's a common coding error to forget the break, tools like Findbugs flag it up for you.

有一个常见的用例,你有多个 case 干预代码的连续语句:

There's a common use-case where you have multiple case statements in a row with no intervening code:

switch (foo) {
    case 0:
    case 1:
        doSomething();
        break;
    case 2:
        doSomethingElse();
        break;
    default:
        doSomeOtherThing();
        break;
}

在那里,我们要打电话给 doSomething 如果 foo 0 1 。大多数工具都不会将此标记为可能的编码错误,因为在案例1 案例0 中没有代码$ c>,这是一种相当常见的模式。

There, we want to call doSomething if foo is 0 or 1. Most tools won't flag this up as a possible coding error, because there's no code in the case 0 prior to the case 1 and this is a fairly common pattern.

这篇关于切换不间断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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