Sunday, January 20, 2008

Language Use Cases

Imagine that you are the customer for a new programming language. What three use cases would be most important to you and why?

Saturday, January 12, 2008

Searching for more Fluent API patterns for Java

Previous posts cover three patterns commonly seen in Fluent APIs in Java.
  1. Method Chaining
  2. Nested Interfaces
  3. Fluent Builder
So far these are the only Fluent patterns that I have seen used successfully in Java. Does anyone have any examples of Fluent APIs in Java that don't use one of these techniques?

Fluent API pattern: Method Chaining

Method Chaining is the simplest and most common pattern for creating Fluent APIs. A great example is in the Binder class in Guice. It allows you to chain methods one after another in a way that describes the desired results. Here is an example from the Guice User's Guide:

binder.bind(Service.class).to(ServiceImpl.class).in(Scopes.SINGLETON);

The simplest implementation of method chaining can be seen in the Java StringBuffer where the 'append' method returns a reference to itself. This is not exactly Fluent since it does not resemble a natural language sentence, but it works the same way.

This can also be seen in an example from a previous post that uses the CustomerCreator:

Customer customer = createCustomer.named("Bob").that(bought.item(CompactDisc).on("02/17/2006"));

The method 'named' returns another instance of a CustomerCreator such that you can chain the 'that' method off of it. Per usual, I strongly encourage you to download the full example source and play with it to see how these Fluent API pattern can be used in conjunction.