Search code examples
fluentfluent-interface

Are there any Fluent interfaces?


I have read about Fluent APIs, where code can be made to read like English, but I can't seem to find any examples of them, as I would like to find out whether they are a reasonable way to make an easy to use interface to a system by non full time programmers. Does anyone have any examples of a fluent interface?


Solution

  • I am the developer of jOOQ, which ships with a fluent API to dynamically construct typesafe SQL queries. An example:

    create.select(FIRST_NAME, LAST_NAME, count())
          .from(AUTHORS)
          .join(BOOKS)
          .using(AUTHOR_ID)
          .groupBy(FIRST_NAME, LAST_NAME)
          .orderBy(LAST_NAME);
    

    The underlying SQL query is "hidden" behind a number of interfaces that model every "step" involved in query creation. This means, .select(Field...) returns an interface providing access to the .from(Table) method, which in turn returns an interface providing access to the .join(Table) method, etc.

    SQL is actually a DSL which is external to Java. With jOOQ (or any other fluent API), SQL can be "internalised" into Java to a certain extent. Unlike with an external DSL, some SQL-specific constructs are hard to be mapped to an internal DSL in Java. An example for this is aliasing.

    See more documentation here:

    http://www.jooq.org/manual/DSL/

    Update:

    In the mean time, I actually ran across another highly interesting fluent API used to construct RTF files from Java. Some example code:

    rtf().section(
       p( "first paragraph" ),
       p( tab(),
          " second par ",
          bold( "with something in bold" ),
          text( " and " ),
          italic( underline( "italic underline" ) )     
        )  
    ).out( out );
    

    See more here:

    http://code.google.com/p/jrtf/