Monthly Archives: July 2011

Functional programming, closures and higher order functions in Java

Somehow exploratory programming (which is what I am doing to learn about game programming) seems to be much easier when coding in a functional style (if that really is what I think it is :-)). I don’t know the domain yet, I don’t even know what kind of game I’m making and creating class hierarchies did not quite work so far. Apparently all I need is a placeholder for some code and a way to pass it around and even if Java is not really interactive I am already making very good progress. I will post more about this in the near future, but for now here are the basics of what I’m doing.
Also this approach has been described before and I’m not claiming it’s original, this is just my take on it and I’m posting it because it is how I ended up coding for my game.

Java is not a functional language (thank you Captain Obvious) but fortunately there is just enough support in the language to build the rudiments needed for programming in a functional style. The most basic thing we need is a function object or a functor and in Java this can be expressed as a single method interface. Here is a functor that takes an argument of type A1 and returns a result of type R.

public interface Functor1 R invoke(A1 a1);

}


Java does not support variable length optional arguments and the only way I know to get around this is to define Functor2 and Functor3 and so on, just define all the variations you need…

public interface Functor2 {

R invoke(A1 a1, A2 a2);
}
public interface Functor3 {
R invoke(A1 a1, A2 a2, A3 a3);
}

The mandatory trivial example, a simple functor that adds two integers:

class Adder implements Functor2 {

@Override
public Integer invoke(Integer a1, Integer a2) {
return a1 + a2;
}
}
...
Adder adder = new Adder();
adder.invoke(2, 3);

Here is a slightly more complex and more “functional” example, the makeAdder function is what it’s called a higher-order function that creates a functor containing the implementation of the add operation. This implementation is contained in an anonymous inner class that will be completely hidden from the outside world and only available through it’s functor interface.

Functor2 makeAdder() {

return new Functor2() {
@Override
public Integer invoke(Integer a1, Integer a2) {
return a1 + a2;
}
};
}
...
Functor2 adder = makeAdder();
adder.invoke(2, 2);

I know it looks ugly but after using this stuff for a while the unimportant boiler plate code kinda fades away and I only see the function code, pretty much the same way LISP coders don’t notice parentheses anymore.

More complex scenarios can be handled with proxies and introspection, preprocessing with apt or maybe even code generation with something like cglib but so far I did not really have a need for something like that. So there you have it, first-class functions in Java, this is pretty much all that is needed to support closures and higher order functions.

Now that we have pseudo first-class functions closures are relatively easy, in Java a closure can simply be simulated as an anonymous inner class and such a class gets access to the enclosing class members and also the local final variables. (You have probably already used closures disguised as various Java “callbacks” and things like the Runnable interface…)
Here is an example of a function that creates three functors that manipulate an “item database”. (If I remember correctly similar examples have been presented in various LISP books.)

void doSomething() {

final Map itemDb = new HashMap();

Functor2 addItem = new Functor2() {
@Override
public Item invoke(String name, Item item) {
itemDb.put(name, item);
return item;
}
};
Functor1 getItem = new Functor1() {
@Override
public Item invoke(String name) {
return itemDb.get(name);
}
};
Functor1 removeItem = new Functor1() {
@Override
public Item invoke(String name) {
return itemDb.remove(name);
}
};

doSomethingWithTheItems(addItem, getItem, removeItem)
}

void doSomethingWithTheItems(Functor2 addItem, Functor1 getItem, Functor1 removeItem) {
addItem.invoke("item1", new Item());
...
}

Observe how the database manipulation functors can be passed to other parts of the code that do not know anything about a hash map that exists somewhere to hold the items.

One more thing, it is not possible to change a final variable, so for instance a primitive value cannot be changed from inside a closure. The workaround is wrapping that variable in a mutable container, I have seen this emulated with a single element array but I use the class below:

public class Reference {

public K v;

public Reference(K v) {
this.v = v;
}

@Override
public String toString() {
return v.toString();
}

@Override
public boolean equals(Object obj) {
return v.equals(obj);
}

@Override
public int hashCode() {
return v.hashCode();
}
}
final Reference var = new Reference(1);

Functor incVar = new Functor() {
@Override
public Integer invoke() {
var.v++;
return var.v;
}
};
incVar.invoke();

This is all, for additional information on the benefits and downsides of functional programming, with or without Java, please consult your nearest search engine.

Did I mention this is an experiment I indulge in? I imagine that most Java programmers will find various flaws but so far it worked well for me and it also seems that as parts of the code get finalized it is pretty easy to convert them to a more conventional Java style. I also know that I could switch to Scala or Clojure (I have used Clojure before but not Scala) but for now I will just wait for Java 7.