[switch] Further unification on switch

Kevin Bourrillion kevinb at google.com
Thu Apr 19 22:19:13 UTC 2018

On Thu, Apr 19, 2018 at 1:44 PM, Brian Goetz <brian.goetz at oracle.com> wrote:

And the reason we think that improving switch is the right primary goal is
> because a "do one of these based on ..." construct is _better_ than the
> corresponding chain of if-else-if, for multiple reasons:

>  - Possibility for the compiler to do exhaustiveness analysis, potentially
> finding more bugs;
>  - Possibility for more efficient dispatch -- a switch could be O(1),
> whereas an if-else chain is almost certainly O(n);
>  - More semantically transparent -- it's obvious the user is saying "do
> one of these, based on ...";
>  - Eliminates the need to repeat (and possibly get wrong) the switch
> target.

#3 is a big one: the more constrained the construct, the quicker the code
is to read and understand. There is less that it *might* be doing, so it's
clearer what it *is* doing.

Enums get even more benefits: unqualified constant names, getting to
sidestep the `==`-or-equals() debate, and the special exhaustiveness stuff.

Indeed, switch rocks.

## Closing the gap

> So, let's take one more step towards unifying the two forms (call this
> UA2), rather than a step away from it.  Let's say that _all_ switches can
> support either old-style (colon) or new-style (arrow) case labels -- but
> must stick to one kind of case label in a given switch:

Holy mackerel. I think this possibly gives us everything we wanted and then

    // also statement switch
>     switch (x) {
>         case 1 -> println("one");
>         case 2 -> println("two");
>     }

Can a single-statement case have a variable declaration as that statement,
and what would be its scope?

#### Look, accidental benefits!
> Many of switches failings (fallthrough, scoping) are not directly
> specified features, as much as emergent properties of the structure and
> control flow of switches.  Since by definition you can't fall out of a
> arrow case, then an all-arrow switch gives the fallthrough-haters what they
> want "for free", with no need to treat it specially. In fact, its even
> better; in the all-arrow form, all of the things people hate about switch
> -- the need to say break, the risk of fallthrough, and the questionable
> scoping -- all go away.

These benefits are so great that you should stop describing them as
accidental. :-)

I think you're saying that *every* switch statement that doesn't require
fall-through can always be expressed in arrowform. If that's right, I'm
very happy. Please make this happen. :-) (I'll still try to think of flaws
if I can.)

Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb at google.com

More information about the amber-spec-observers mailing list