Tuesday, November 19, 2013

Interesting usage of a Java switch

In implementing some trivial mappings between a POJO and an SQLite cursor, there is the possibility of forgetting to map some columns. In general I prefer enums over static final constants whenever possible (and enums allow me to annotate other column metadata that I can use to create the table). But here I've found an interesting usage of a switch statement.

Given the enum:

If I were to add a new column, a compiler warning can thankfully remind me with a warning. 

Here's a way to take advantage of that in code that would otherwise be linear without the switch:

You can see that I switched on the enum with ordinal 0, but it doesn't really matter as long as the first case matches the switch constant; when no breaks are used all of the cases fall through to the next. Since I intend to cover every enum value only once, there's no need for a for loop to iterate the enum values.

That's another advantage to this approach over for (Column e : Column.values()) switch (e) {} is that this way the values can be processed in any order, rather than just incrementing ordinals.

No comments:

Post a Comment