Thursday, November 21, 2013

Try/finally to do post-super actions with return

A common pattern for overriding a super method requires keeping the return result of the super method in a temporary variable:


But this temporary variable can be avoid using try/finally:



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.