Chris wrote about functional programming in Java. As an example he used Google Collections which “is a suite of new collections and collection-related goodness for Java 5.0″.

Looking at his post he gives the following code on how to use Goolge Collections

files = Iterables.transform(
  Iterables.filter(
      Iterables.filter(getPagesList(),WebPage.class),undeletedPages),
  new PagesToFilesTransformation()))

This is very verbose and hard to read. Mostly due to the static method calls and the seperation of the first “filter” and the “new PagesToFilesTransformation()” parameter. Using a static import we can reduce this to:

import static Iterables.*;

transform(
   filter(
      filter(getPagesList(),WebPage.class), undeletedPages),
   new PagesToFilesTransformation()))

Better. I’ll show you how to make this even more readable with a fluent interface. I use the following example for this:

List names = Arrays.asList("Stephan", "Chris", "Mike", "Miha", "Katrin");

Iterable filtered =  Iterables.filter(
  Iterables.filter(names, or( isEqualTo("Katrin"), isEqualTo("Miha"))),
    lengthLessThan(5)) ;

We want to move this code to a fluent interface. Martin Fowler wrote about Fluent Interfaces on his bliki and there is a entry on Wikipedia. They were made popular by JMock as a way to specify mock expectations.

logger.expects(once()).method("setLoggingLevel").with(eq(newLevel));

What is a fluent interface though? For me it’s an interface to an API which is more consistent and readable. Which helps you do several steps with an API in a correct way. It’s often implemented with speaking method names and call chaining. These together create the illusion of natural, descriptive language. When the chained methods return the correct type, most often it’s impossible to call the wrong methods or methods in the wrong sequence. Therefor fluent interfaces create better readable code with less bugs. Which distinguishes them from domain specific languages (like in Ruby on Rails), macro programming (Lisp) or plain language constructs (methods which take closures) like “[1..5].each { … }”. The differences is fluent ;-) “5.times.each {…}” could be considered a simple fluent interface.

The most recent fluent interface in Java with some fame is Quaere, a kind of LINQ for Java for querying object graphs. There even is a promising Quaere API for JPA. I really think fluent interfaces are useful, although others think they are stupid. I keep to myself what I think is stupid and we see where this all is going to.

Back to our example. I’ve recently shown how to create a fluent interface for object creation. One for Google Collections might look like this:

Iterable<T> filtered =
    with(names)
   .filter( or(isEqualTo("Chris"), isEqualTo("Miha")))
   .filter(lengthLessThan(5));

This example isn’t optimal, but much more readable than the one given by Chris. The or() part could be improved because it doesn’t look very nice. This will change with closures. Fluent interfaces will boom with closures in Java 7.

In the comment to his blog post, Chris mentions “Making a fluent interface to do this might be a little risky, because I think there’s an expectation* that a method like Iterable.filter() wouldn’t modify the source iterable itself, but rather would return a new, filtered iterable.” We do not need to modify the Iterable, we only hold a reference and create new fluent interfaces on the fly as needed. Our code to enable a fluent interface for Google Collections this is rather simple:

public class FluentIterable<T> implements Iterable<T> {
  private Iterable<T> iterable;

  public FluentIterable(Iterable<T> iterable) {
    this.iterable = iterable;
  }

  public static <T> FluentIterable<T> with(Iterable<T> iterable) {
    return new FluentIterable<T>(iterable);
  }

  public FluentIterable<T> filter(Predicate<? super T> predicate) {
    return new FluentIterable<T>(
        Iterables.filter(this.iterable, predicate)
    );
  }

  public Iterator<T> iterator() {
    return this.iterable.iterator();
  }
}

This example has several main points. The with() static method call is descriptive and creates a fluent interface object for us to hold the Iterable object. Second most methods in fluent interfaces return the object itself. We create a new fluent interface object in filter to wrap the filtered iterable and enable chaining. My last example with object creation did hold the same bean and did not create new objects on the fly. This really depends on what should be done. We could have set the new iterable instead of creating a new wrapper like this:

  public FluentIterable<T> filter(Predicate predicate) {
    Iterable filtered = Iterables.filter(this.iterable, predicate);
    this.iterable = filtered;
    return this;
  }

This mostly depends on your style and if you think immutable objects are good or bad. For this I prefer the immutable Fluent Interface object over the mutable. Perhaps this is a pattern.

Conculsion:: A fluent interface for Google Collections would be useful. It’s more readable, less error prone and flows. Although my example works and is usable, there needs to go more work into a fluent interface for Google Collections to make it useful. For example support more Predicates and support transformations.

Thanks for listening.


6 Responses to “Creating a fluent interface for Google Collections”  

  1. Gravatar Icon 1 Kevin Bourrillion

    Tell you a secret, I’ve hated Iterables.transform() and Iterables.filter() ever since about a month after I wrote em. And your solution to the problem is an interesting one which I had not thought of.

    The other fix that I had in mind: make Function and Predicate into abstract classes which have the transform(), filter(), and other related methods right there on them. To me, this is a much more sound idea from an OO perspective than saying you have to go call out to some static “Iterables” method (which is entirely nonobvious).

    As well, it means that in the resulting code, filters and transforms appear in “infix”, not prefix form, which I find a lot easier to read.

    The down side of all this: *occasionally*, but not often, someone does want to implement Predicate/Function from an existing class that already has a superclass, thankyouverymuch. There are some ways we could deal with that, though. Anyway, though, as time permits I’ll draw up a three-way comparison of the apis and see if we can shake out which one’s best.

  2. Gravatar Icon 2 stephan

    Hi Kevin,

    To tell you a secret, I’ve thought about the same thing. When writing about fluent interfaces for object creation

    http://stephan.reposita.org/archives/2007/10/10/fluent-interface-and-reflection-for-object-building-in-java/

    I was wondering if fluent interface is a concern of the Person bean which it creates or if it’s a different concern. When this should be the case, a different class called PersonFluentInterface is good practice, as each class should encapsulate one concern, not different ones. This also makes the Person bean smaller and easier to understand. When being interested in the fluent interface, one could look into PersonFluentInterface and see the methods and code - and not be confused with the Person concerns.

    “Anyway, though, as time permits I’ll draw up a three-way comparison of the apis and see if we can shake out which one’s best.”

    That would be great and I would be interested in the result. Thanks for your comment.

  3. Gravatar Icon 3 Brian Slesinsky

    I think if you’re going to do a fluent interface, it should be using a builder pattern:

    Iterable filtered =
    Iterables.with(names)
    .addFilter(or(isEqualTo(”Chris”), isEqualTo(”Miha”)))
    .addFilter(lengthLessThan(5))
    .finish();

    The idea is that all the intermediate objects should be instances of IterableBuilder, which has the “fluent” methods. The finish() method converts an IterableBuilder back to a plain Iterator. This way the “fluent” methods don’t clutter up the interface when you’re not modifying the Iterable.

    Also, if there is an IterableBuilder object then I think it’s fine to modify-in-place rather than creating a new instance on each method call, which may be important for performance.

  4. Gravatar Icon 4 stephan

    Hi Brian,

    I think a fluent interface uses several patterns and provides several solution. The solutions can be Building-of-objects or can be modelling business logic (mostly when used with closures). As Java does not support closures yet, most fluent interface applications currently fall into the builder domainBeside that another pattern fluent interfaces use is the Facade pattern. But fluent interfaces are more than variants on facades and builders. They are a mixture of DSL, builders, facades, readable APIs, context selection and other ideas. So yes in this case it’s mainly a builder implementation. Not in other cases though.

    I thought about the finish() method. Usually I use a create() or make() method and would like to use do() for executing filters (Java doesn’t like do though). But sometimes I find it more fitting to exend the base class and drop the creation method call as a last call in the chain.

  5. Gravatar Icon 5 Jimmy Bogard

    I wouldn’t say they’re stupid per se, as I used them extensively when creating NBehave. There are definitely some caveats with them, especially when trying to debug them.

    At least in C#, an entire block of fluent interface code done through method chaining counts as one line of code to the debugger, so you don’t know which method call in the chain is giving you issues. This can get extremely annoying when you have particularly large fluent interface blocks.

    I think fluent interfaces are becoming popular because:
    - Building real (or external) DSLs is hard
    - Still no solid cross-platform dynamic language support, i.e. JRuby or IronRuby
    - Fluent interface APIs can be used with familiar languages like Java and C#

    We use NUnit a lot, but get very jealous when we see our QA guys using RSpec and Watir. All of the noise of the syntax goes away and it becomes much more readable. But until these dynamic languages can run easily in the JVM or the CLR, and have great IDE support, fluent interfaces are definitely the way to go.

  6. Gravatar Icon 6 stephan

    Hi Jimmy, yes sure. I agree with you why fluent interfaces are becoming popular. Though I don’t agree with the common opinion that fluent interfaces are a poor mans DSL. They are more than that (and less than that). They have different goals than DSLs. I guess I have to write a paper to make myself clear.

    About RSpec and Watir: I’ve been wrestling with an parser for Wiki syntax for the last 7 years without success. Writing parsers is currently very hard. Because of this, Radeox as a wiki engine has still a regex ‘parser’ no real parser.

    People like Ruby because they can create a language without a parser. When there are easy parser tools for the JVM or CLR - and Tatoo is certainly a first step - every developer can writer a parser which ‘maps’ a DSL to a base language on the JVM or CLR. Then Ruby with it’s language defining abilities will look much less adorable.

    And after 15 years with dynamic languages (TCL, Perl, Python, Ruby) I it will be a very hard way to make great IDEs for them. The current Grails/Groovy support in IDEA is the best you can get - and it’s nice. But poor compared to the Java support. They can gather runtime information to make the IDE understand the code better, though I guess there are some natural limits to that.

Leave a Reply



RSS