I came across this code in a Java refactoring project.
switch ( cmd ) {
case 0:
//Process A
// fall through
case 1:
case 2:
//Process B
break;
default:
//Process C
break;
}
At first glance, case 0
seems to perform only processing A
, but if you look closely, case 0
does not have break
, so it actually does processing B
as well. !!
At first, did you forget to write break
? I thought, but apparently it behaved as specified.
In this way, the notation that intentionally omits break
is called ** fall through **. If you look closely, you can see it in the comments.
This fallthrough is a very interesting technique, but I thought it would be misleading and a breeding ground for bugs, so unfortunately I decided to replace it with the ʻif` statement.
if ( cmd == 0 ) {
//Process A
}
if ( cmd <= 2 ) {
//Process B
} else {
//Process C
}
Well, was it simpler before the change? It is subtle. But I no longer have to worry about misreading.
However, if cmd
is of type String
, you can't write it like this. to worry.
If there is a better way to write it, please let me know.
I was curious about the situation in other languages, so I took a quick look.
break
is omitted in the switch
statementbreak
in the switch
statementbreak
if you do nothing in the case
statement.
--You can do something like fallthrough with goto
.switch
statement--Perl (specify next
)
--Swift (specify fallthrough
)
--Go (specify fallthrough
)
switch
statement but cannot fallthrough--Ruby (case
statement)
--Scala (match
statement)
--Kotlin (when
statement)
switch
statementbreak
to censor it.It depends on the language! I learned a lot.
Recommended Posts