The source code in this project (and its accompanying presentation) demonstrate some principles of functional programming using standard Java.
The concepts fall into the following categories:
In order to get rid of the dreaded null pointer exceptions, you can
have a function accept parameters of type Option. Only two classes
implement this interface: None
and Some
.
- None: returns
false
whenisPresent()
function is called. - Some: returns
true
whenisPresent()
called, and returns results fromvalues()
We can then have a function like:
public FlexiMap( Option<Closure> putfn, Option<Closure> getfn ) {
if(putfn.isPresent())
onPut = putfn.get();
if(getfn.isPresent())
onGet = getfn.get();
// ...
}
This process makes it less likely to encounter with null
values.
The Closure interface has a single... ahem... function inside:
Object apply(Object ...objects);
This allows anonymous inner classes to pass simple functions around. Of course, I find the syntax for anonymous inner classes quite icky, and prefer to create private inner classes instead:
private class DefaultValueForNull implements Closure {
final Object defaultValue;
public DefaultValueForNull(Object value) {
this.defaultValue = value;
}
public Object apply(Object... objects) {
if (objects[0] == null)
return defaultValue;
else
return objects[0];
}
}
To demonstrate the concept of creating specialized versions of a Map
through
composition (instead of inheritance), we took these unit tests from
the Apache Commons Functor library, but instead of using their libraries,
we used our own Closure
classes (see these this code).
Same principle, different approach.