Saturday, January 12, 2008

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.

No comments: