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(session.save(persistableObject);
      }
    });

To accomplish the same thing, though in a more error prone manner, we might just do the following:
  session.open();
  Object obj = session.save(persistableObject);
  session.close();
Now you say, well that looks better. Well yes and no. The problem with this approach arises when the logic in between session.open() 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
  equityOption.substitute_with(basketOption)
  equityOption.expire
  basketOption.activate
end

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.

Anonymous Classes: Java's Synthetic Closure

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

I've been meaning to write this blog post since late last year when I revisited the Java world after a hiatus of adventures in the Ruby and Python worlds. When I was a Java advocate (many moons ago it seems now), I really didn't appreciate the true beauty that is anonymous classes. I saw them as ugly and reducing code readability. Syntactically I still agree with that assessment, but conceptually I couldn't disagree more now. When revisiting Java last year for a client, I found myself really missing blocks from the Ruby world. The following common snippet of code in Ruby passes a block to a method:


  connection = Net::HTTP.new
  connection.use_ssl = true if ssl?
  connection.start do |connection|
    request = yield connection if block_given?
    request.basic_auth(@login, @password) if require_auth
    response = connection.request(request, body)
    handle_rest_response(response)
    response
  end

[This code is taken from the Twitter4R project and is slightly paraphrased.] What we are doing here is wrapping a block within a begin/end API construct. So the previous snippet of code is effectively the same as (and in fact this is the way the above gets executed):

  connection = Net::HTTP.new
  connection.use_ssl = true if ssl?
  connection.open
  request = yield connection if block_given?
  request.basic_auth(@login, @password) if require_auth
  response = connection.request(request, body)
  handle_rest_response(response)
  connection.close
  response

Why is the first so much better from a code maintainability and readability perspective? In my view the main benefits include (but are not limited to):
  • Passing in a block ensures we close the connection (as in the above code example). If we forgot to "end" the block in the first snippet we would get a SyntaxError in Ruby which would remind us to close the block (and thus connection implicitly). Which means less likely to introduce defects related to not closing connections unlike second code example.
  • Putting the code to be executed passed in with a block improves code readability and in my view that is always a good thing. It is more obvious to fellow developers what is going on.
Now in Java we can't simulate the code above in Java syntax...or can we? I suggest with a few more {} and () and ; we can accomplish the same as above. And if we cover our eyes with our hands and squint through the gaps in our fingers, we might be happy with the way it looks (OK, it is ugly, but this is the world of Java people!). Below is an example of a similar technique as the Ruby example above, but this time in Java and related to database transaction (specifically in Hibernate3 below):

// In PersistenceExecutionResult.java we define the following....
public class PersistenceExecutionResult {
  private Object result;
  public PersistenceExecutionResult(Object theResult) {
    result = theResult;
  }

  public Object getResult() { return result; }
  public void setResult(Object theResult) { result = theResult; }
}

// Now in PersistenceExecutor.java we define....
public interface PersistenceExecutor {
  public abstract PersistenceExecutionResult execute() throws Exception;
}

// Now in BaseDAO.java we have the following....
public class BaseDAO {
  public Long create(BaseObject persistableObject) throws Exception {
    final Session session = ....; // get session somehow - irrelevant to demonstration of synthetic closures in Java
    return (Long)executeTransaction(session, new PersistenceExecutor() {
      public PersistenceExecutionResult execute() {
        return new PersistenceExecutionResult(session.save(persistableObject);
      }
    });
  }

  // other stuff, but just adds noise to example.

  protected ExecutionResult executeTransaction(Session session, PersistenceExecutor executor)
    throws Exception {
    Transaction tx = null;
    PersistenceExecutionResult result = null;
    try  {
      tx = session.beginTransaction();
      result = executor.execute();
      tx.commit();
    } catch (Exception e) {
      if (null != tx) tx.rollback();
    } finally {
      session.close();
    }
    return result;
  }
}

Now what on earth is going on? Anyone? Well I will explain in a subsequent posting and compare it to the equivalent code without using anonymous classes to wrap begin/end API constructs. Right now I am too tired and lazy, but I will explain soon, fear not. Notes: the above works with JDK 1.4 because when I wrote this it had to be 1.4 compliant (therefore fancy generic interface definition to DAO was not possible). I have only used JDK 1.5 (aka 5) and not 6. Is there a nicer way of doing this in 6?

RESTful API & Web Service Statuses

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

As I have browsed and read newsgroups, mailing lists, articles and even books related to RESTful APIs and Web Services very few tackle the issue of which HTTP status messages are most relevant for the communication at hand. Below is a list of the few HTTP status codes that I most commonly use in the development of my own APIs and Web Services for my clients:

  • 404 “Resource Not Found”: Yes, you read that right. When a resource of a specific given ID does not exist in our datastore (whether due to it being an invalid ID or due to the resource having been deleted from our datastore). For example, “GET /people/2349594934896107” may not exist in our database, so what do we display? Just the bare “people/show” view with a flash message saying no person with that ID exists? I should say not – at least not in our RESTful world. However, if we are using something like acts_as_paranoid or home-grown paranoid delete mechanism and we know the resource used to exist in our datastore, we could respond with 410 “Gone”. The benefit of this is that we are communicating something useful back to the RESTful consumer, whether that is an end-user or another application or web service.
  • 401 “Unauthorized”: Returned when consumer either did not provide credentials to view restricted resource or the authentication and/or authorization failed. This assumes your application uses the Basic or Digest HTTP Authentication scheme as according to the HTTP protocol the server needs to respond with specific HTTP headers in various circumstances of returning this status code.
  • 503 “Service Unavailable”: Used when taking the site down for maintenance. I find this very handy indeed when upgrading the RESTful web services I deploy at work. For my projects I create a stub Rails application that responds with a 503 for each valid type of request that comes in. Clients of my services are usually services themselves or other applications, so this helps client developers that consume my web services know that this is a temporary blip and should be due to schedule maintenance (and a good reminder for them to check the emails I sent them over the weekend instead of ignoring them). The best and easiest way to do this is to create a new routes.rb file that contains all valid requests and points it to a controller/action that responds with a 503.
  • 201 “Created”: Very handy, especially in the context of designing RESTful web services. Status should be sent when replying to a POST that created a new resource on the server.
  • 202 “Accepted”: Yes, slightly obscure, but very handy. Signals to consumer of application (whether end-user human or REST client application) that a long running/executing job has been submitted for processing, but we do not yet know the outcome of the “job” or “process”. Of course, as with all of the above, to an end-user we would render a nicely designed web page telling them this, but if for some reason a bot (authorized or not) or web services client accessed our application, they would be able to determine some useful information from the status.
Please let me know any other HTTP status codes you find most useful when designing RESTful APIs. Update [2007-08-20]: Below are another couple of HTTP status codes, explanations and examples to aid in the more consistent development of true RESTful APIs:
  • 301 "Moved Permanently": This is a good one when deprecating RESTful APIs. For example, say you are no longer going to support the resource (and all related individual CRUD and custom methods) /corporate_bonds and instead provide the following resource "/bonds/:type" where :type might include corporate, municipal and government. Whenever a valid request is made to the "/corporate_bond" resource I will return a 301 HTTP status to the consumer to inform them that they need to use the new API.
  • 307 "Temporary Redirect": This is a nifty little status when you have temporarily suspended a resource, for example a "/users" resource. If a user is delinquent on their latest monthly installment, you want to start redirecting all calls to their profile, etc. to a temporary page that informs consumers of the RESTful site that this account is not current. There are probably many other good uses of this too. If you know of one, please leave a comment and educate me further.

Story-level BDD specing using rBehave

Written on 12:51:00 PM by S. Potter

For those in the BDD world that have been asleep at the wheel over the last month or two, Dan North has released rBehave which wraps around RSpec and allows developers to spec their code at the story level, which has been missed in RSpec (though I don't know what I would do without RSpec). Dan mentions that he is discussing integrating his work into RSpec at some point in the future, but in the meantime Dan's rBehave framework is currently at version 0.3.0 and is available for install as a Ruby Gem as usual: sudo gem install rbehave Dan gives an example of rBehave using a bank transfer story on his blog. Below I give another example of authenticating a user:

require ‘rubygems’
require ‘rbehave’
require ’spec’ # for "should" method

require ‘user’ # the actual application code

Story "authenticate user",
%(As a user of the system I wish to authenticate and access my account information.) do

  Scenario "correct password is supplied but user has been suspended" do
    Given "my user account is created", User.new do |user|
      @user = User.new
    end
    Given "my username is", "myusername" do |username|
      @user.username = username
    end
    Given "my password is", "mypassword" do |password|
      @user.password = password
    end
    Given "my user account has been suspended", true do |suspended|
      @user.suspended = suspended
    end
    When "I attempt to authenticate with", "mypassword" do |password|
      @authenticated = @user.authentiate?(password)
    end
    Then "my user account should respond with authentication status of", false do |status|
      @authenticated.should be(status)
    end
  end

  Scenario "correct password is supplied and user is active and verified" do
    Given "my user account is created", User.new
    Given "my username is", "myusername"
    Given "my password is", "mypassword"
    Given "my user account has been suspended", false
    Given "my user account has been activated", true do |activated|
      @user.activated = activated
    end
    When "I attempt to authenticate with", "mypassword"
    Then "my user account should respond with authentication status of", true
  end

  # A few other scenarios go here, like non-activated user (but not suspended), etc.
  # Left as exercise to the reader.
end
Please note, i do not need to restate the Given, When or Then blocks passed in after they are defined once!