Skip to content
master
Switch branches/tags
Code

Latest commit

 

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
src
 
 
 
 
 
 
 
 
 
 

Function Programming Ideas for Java

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:

Optional Parameters

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 when isPresent() function is called.
  • Some: returns true when isPresent() called, and returns results from values()

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.

Closures

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];
  }
}

Composition

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.

About

Demonstrating some functional programming principles in Java... it isn't as bad as you'd think (but still not nice)

Resources

License

Releases

No releases published

Packages

No packages published

Languages