default branch placement in switch

Kevin Bourrillion kevinb at google.com
Mon Dec 11 18:16:11 UTC 2017


On Fri, Nov 3, 2017 at 5:25 PM, Brian Goetz <brian.goetz at oracle.com> wrote:

>
> or plan to eventually get to a place where default always comes last, even
> for "int" switches. If we want to get to the latter, we should start
> warning on this construct now.


I favor starting to warn and eventually forbidding default in any position
but last for all constructs that have it.

A switch with the default in the middle is extremely weird and confusing.
If I'm reading code to understand what happens when i == 3, and I read as
far as

switch (i) {
  case 1:
    justOneStuff(); break();
  case 2:
    justTwoStuff(); break();
  default:


... then I immediately assume that this must be where execution is
continuing. Worse, even if I do notice that there are more case labels to
follow, and I resume searching for a `case 3:`, then when I don't find one
I now risk making *another* error and forgetting to jump *back* to the
default.

This is kind of insane. At first I was less worried because I thought
"surely no one is actually doing this"... then I browsed our codebase....
yikes.

We should at least strongly consider this.



On 11/3/2017 5:10 PM, Tagir Valeev wrote:
>
>> Hello!
>>
>> Currently the default branch can be placed in any place inside the
>> switch operator, e.g. like this:
>>
>> switch(i) {
>> case 1: System.out.println("one");break;
>> default: System.out.println("other");break;
>> case 2: System.out.println("two");break;
>> }
>>
>> In this case behavior does not change on the order of case blocks.
>> However in pattern matching the order of cases usually matters: if
>> some pattern matches, this means that the subsequent patterns will not
>> be checked. Does this mean that with pattern matching the default
>> branch makes all the subsequent case blocks unreachable? Or default
>> can still be located anywhere and is checked only after any other
>> pattern?
>>
>> With best regards,
>> Tagir Valeev
>>
>
>


-- 
Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb at google.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20171211/61f7fe77/attachment.html>


More information about the amber-spec-experts mailing list