PUBLIC OBJECT

Java language tweak: protected switch

I have an enumerated type, and it's possible that I'll be adding more values in the future.

public enum Office {
  CALGARY, REGINA, TORONTO, BERLIN;
}`</pre>

Somewhere in the code, I switch on this type:
<pre>`public CurrencyCode getCurrencyForPayingEmployees(Office office) {
  switch(office) {
    case CALGARY:
    case REGINA:
    case TORONTO:
      return CurrencyCode.CAD;
    case BERLIN:
      return CurrencyCode.EUR;
  }
}`</pre>

Unfortunately, this doesn't compile. Javac will tell me that the method doesn't always return, because it doesn't know that I've covered all applicable cases. I appease the compiler by adding this line at the end of the method:
<pre>`    default:
      throw new AssertionError();`</pre>

Now whenever I add a new office I have to scour through the code to find the switch statements and add the appropriate behaviour. I get no compiler help from this, so if I miss one, I'll end up getting `AssertionError`s in test or production.

The classical solution for this is the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern), but it's somewhat verbose and doesn't work very well if when I don't control the enum that I'm switching on.

What if Java had a 'protected' switch statement that protected me from forgetting an element? The syntax would be similar:
<pre>`public CurrencyCode getCurrencyForPayingEmployees(Office office) {
  **_protected_** switch(office) {
    case CALGARY:
    case REGINA:
    case TORONTO:
      return CurrencyCode.CAD;
    case BERLIN:
      return CurrencyCode.EUR;
  }
}

But there are a few differences:

  • the compiler enforces that every type is covered, and shows a compiler warning if a particular enum element is not present.
  • if we return from all cases, we don't need an extra 'return' statement at the bottom to handle the nonexistent other case.

    If ever I have the time, I'll see if I can hack javac and contribute this to KSL.