Dr. David J. Pearce

Fall-Through by Default for Switch Statements?


The switch statement has a long history, and most languages support it or something similar.  In my experience, I found it to be very useful — both for conciseness, and also improving performance.  With the recent release of Java 7, you can finally switch over strings.

In Whiley, the syntax for switch statements currently looks like this:

for token in modifiers:
    modifier = null
    switch token.id:
       case "PUBLIC":
       case "public":
          modifier = ACC_PUBLIC
          break
       case "FINAL":
       case "final":
          modifier = ACC_FINAL
          break
       ...
       default:
          throw SyntaxError("invalid modifier",token)

(This excerpt is based on my Java Assembler/Disassembler benchmark)

Now, I’m having something of a dilemma over this syntax: should I support fall-through case statements or not?

As you can see from above, my initial reaction was: yes.  But, I’m starting to think this is a really bad idea and there are a few reasons:

Now, of course, I’m not the first to think along these lines (see e.g. [1][2][3]) and, in fact, I’m probably being a bit slow on the uptake here!

Several languages (e.g. Go, CoffeeScript, Pascal) do not support fall-through by default. For example, Go supports an explicit fallthrough statement, which might look something like this in Whiley:

for token in modifiers:
    modifier = null
    switch token.id:
       case "PUBLIC":
          fallthrough
       case "public":
          modifier = ACC_PUBLIC
       case "FINAL":
          fallthrough
       case "final":
          modifier = ACC_FINAL
       ...
       default:
          throw SyntaxError("invalid modifier",token)

Go is quite interesting as it provides multi-match case statements as well, which might look like something like this in Whiley:

for token in modifiers:
    modifier = null
    switch token.id:
       case "PUBLIC","public":
          modifier = ACC_PUBLIC
       case "FINAL","final":
          modifier = ACC_FINAL
       ...
       default:
          throw SyntaxError("invalid modifier",token)

I really like this syntax (which I think is originally from Pascal). In Pascal, you can provide ranges as well which certainly makes sense.

So, all things considered, I’m convinced it is a mistake to support fall-through by default in Whiley.  Fortunately, it’s not too late for me to correct this!

The big question then is: do I support explicit fallthrough, multi-match cases or both?