[JAVA] I met a great switch statement

I met a great switch statement

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.

It was a technique called fallthrough

In this way, the notation that intentionally omits break is called ** fall through **. If you look closely, you can see it in the comments.

I replaced it with the ʻif` statement

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.

Languages that can and cannot fall through

I was curious about the situation in other languages, so I took a quick look.

Languages that fall through if break is omitted in the switch statement

Languages that get angry if you omit break in the switch statement

Languages that explicitly specify fallthrough in the switch statement

--Perl (specify next) --Swift (specify fallthrough) --Go (specify fallthrough)

A language that has a syntax similar to the switch statement but cannot fallthrough

--Ruby (case statement) --Scala (match statement) --Kotlin (when statement)

Languages that do not have a syntax equivalent to the switch statement

Language in which all blocks that meet the conditions are executed

It depends on the language! I learned a lot.

Recommended Posts

I met a great switch statement
switch statement
Java switch statement
Switch statement range specification
Studying Java-Part 11-switch statement
Find a Switch statement that can be converted to a Switch expression
[Swift] switch statement using tuples
I made a chat app.
Let's understand the switch statement!
A story that I finally understood Java for statement as a non-engineer