Sunday, September 10, 2006

Closures in Dolphin

A proposal for adding closures to Java has been crafted by none less than: Gilad Bracha, Neal Gafter, James Gosling and Peter von der Ahé. With proponents such as these I have high hopes that Sun will finally see reason and include it JDK7. Our state machine:
interface Condition {
    boolean isFulfilledBy(Event e);
}

interface Action {
    void perform();
}

interface State {
    void addTransition(Condition condition, Action action, State nextState);
}
is used like this to set up a two transitions:
bootState.addTransition(
         new Condition() {
             public boolean isFullfilledBy(Event e) {errorService.hasErrors();}
         },
         new Action() {
             public void perform() {logMessage());},
         errorState);
bootState.addTransition(
         new Condition() {
             public boolean isFullfilledBy(Event e) {((BootEvent)e).isStarted();}
         },
         new Action() {
             public void perform() {displayIdleScreen();},
         idleState);
It can now be cleaned up to look like this:
bootState.addTransition((Event e){errorService.hasErrors();}, (){logMessage();}, errorState);
bootState.addTransition((Event e){((BootEvent)e).isStarted();}, (){displayIdleScreen();}, idleState);
Since most of our flows consist of many states and more transitions our code will become a lot more compact and easier to read. The code above will work without any changes to our state machine API. The reason for this is called closure conversion and it basically allows you to use any class with one abstract method with closure syntax. The typical usage is interfaces with one method but abstract classes with one abstract method will probably also be allowed. I'm looking forward to Dolphin. The verbs are finally making their way into the kingdom of the nouns.

No comments: