Anonymous Classes: Java's Synthetic Closure, Part 2

Written on 10:16:00 PM by S. Potter

So in the last installment we saw something like the following (paraphrased) in Java:

    executeTransaction(session, new PersistenceExecutor() {
      public PersistenceExecutionResult execute() {
        return new PersistenceExecutionResult(;

To accomplish the same thing, though in a more error prone manner, we might just do the following:;
  Object obj =;
Now you say, well that looks better. Well yes and no. The problem with this approach arises when the logic in between and session.close() is more involved. If we had 10 lines of code between the open/close markers and we came to refactor the logic, but omitted the call to close, our tests (if they are purely state-based tests from the TDD world) would probably not catch this omission at the level we would want to catch it. Remember the more levels you need to debug to find the issue the more time you have wasted not doing useful work on new stories or fixing defects, etc. Of course, in the Ruby world where closures are just there for the taking, we don't have to justify ugly looking code to help package reusable "wrapper" logic like above. In a Ruby project that utilizes ActiveRecord we can simply write:

# When a corporate action like merger, spinoff, etc. occurs for an issuer, usually 
# a new option has a basket underlying instead of just a set of equities, so code might 
# look like the following.
Option.transaction(equityOption, basketOption) do

So that I don't sound completely smug to my Java friends, I will let you decide which code snippet looks more beautiful!:) Update: One of my Java friends says there are no closures yet in Java 6, but there are talks about closures in 7 (or will it be version 96 next?), but it is all up in the air.

If you enjoyed this post Subscribe to our feed

No Comment

Post a Comment