Friday, January 07, 2005

Decreasing functor syntax in Java

Functor, closure, functional, operator, executor: there are many names in Java for the same thing, a class which encapsulates a single generic operation than can be handed around like the unsyntactic anonymous function available in other languages.

For a while, I've used some variation of this model:

public interface Closure {
    void execute();
}

Typical use:

new Closure() {
    public void execute() {
        System.out.println("Ni!");
    }
}

This is perfectly adequate when you create such a thing and pass it around. But what if you are looking to use it immediately? I sometimes see this:

new Closure() {
    public void execute() {
        System.out.println("Ni! Ni!");
    }
}.execute();

The example is contrived, but the principal is easy to grasp: there is a shorter way to do this. Try instead:

public abstract class ImmediateClosure {
    protected ImmediateClosure() {
        execute();
    }

    public abstract void execute();
}

new ImmediateClosure() {
    public void execute() {
        System.out.println("Ni! Ni! Ni!");
    }
};

Shorter. That's all I'm saying.

1 comment:

Anonymous said...

Nice idea, although it is not exactly "intention revealing". i.e. it is not common practice for constructors to do much more than initialize the state of the object.

Also, you can run into trouble due to the execute() method being called before construction is complete. Try this out:

new ImmediateClosure() {
private Date today = new Date();
public void execute() {
System.out.println("Today is: " + today);
}
};