Should the default case of switch statment have a break?
Oracle示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString ="January"; break; case 2: monthString ="February"; break; case 3: monthString ="March"; break; case 4: monthString ="April"; break; case 5: monthString ="May"; break; case 6: monthString ="June"; break; case 7: monthString ="July"; break; case 8: monthString ="August"; break; case 9: monthString ="September"; break; case 10: monthString ="October"; break; case 11: monthString ="November"; break; case 12: monthString ="December"; break; default: monthString ="Invalid month"; break; //why is there a switch statement here? } System.out.println(monthString); } } |
页面解释
Technically, the final break is not required because flow falls out of
the switch statement. Using a break is recommended so that modifying
the code is easier and less error prone. The default section handles
all values that are not explicitly handled by one of the case
sections.
我不确定第二句话是否证明了switch语句中使用break是合理的,或者说在结尾添加break语句会减少代码的错误发生率。如果我在默认情况下抛出一个异常,那么是否有必要事后调用break,或者这是一种浪费?在Netbeans里是红色的!出现在无法访问的break语句旁边,但编译良好。
关于可读性,如果满足条件时运行的代码跨越多行,应如何格式化case块?例如,不是只有
我使用开关来测试用户是否输入了选项1、2或3的数字。
I'm not sure if the second sentence is justifying the use of breaks in switch statements in general or is specifically saying adding a break statement to the end makes code less error prone.
后者。
If I'm throwing an exception in the default case is there a point to calling break afterwards or is this a waste?
废物。非新手认识到抛出异常实际上是一种突破。使代码健壮是一回事,试图对初学者和白痴进行防弹是浪费时间的。他们只能用其他方法来打破它。
In Netbeans a red ! appears beside the unreachable break statement but it compiles fine.
是的,但你不想要红色的!把它扔掉。
Regarding readability, how should a case block be formatted if the code that runs when the condition is met spans several lines? For example instead of just monthString ="January"; there's 10 lines of code with loops and things?
考虑将其放在单独的方法中。
I'm using the switch to test if the user entered the number for option 1, 2 or 3.
在这种情况下,您需要一个默认值吗?开关不需要。
我认为违约在大多数情况下是一个非常糟糕的主意。异常可能是传递给switch语句的无效值,您需要对此做些什么(抛出异常,显示消息,无论什么)。否则,每一个可能的值都应该有一个大小写,即使它是空的,这样就可以清楚地看到该值是有效的,但是您打算什么都不发生。
虽然这不是必需的(因为它将在没有break语句的情况下退出),但我认为在默认情况下加入
1 2 3 4 | if(true) do x; else do y; |
VS
1 2 3 4 5 | if(true) { do x; } else { do y; } |
以苹果著名的ssl/tls bug为例,https://www.imperial紫色.org/2014/02/22/applebug.html
如果在默认情况下抛出异常,则不会执行中断,因此您可以将其放在一边。我个人在处理一般的开关时使用大括号来避免不好的可读性。
例如:
1 2 3 4 5 6 7 8 9 10 | switch (variable) { case 1: { code; mode code; break; } default: { break; } } |
没有大括号,但是缩进度很好,可读性也很好。例子:
1 2 3 4 5 6 7 8 | switch (variable) { case 1: code; mode code; break; default: { break; } |