Builders with a Fluent Interface

We use the approach described by the Builder Pattern to ease the creation of objects, especially complex objects. The premise is simple, we slowly gather the parts we want, until we build a complete object.

It wasn't until I started using Builders with Fluent Interfaces, I started to feel more comfortable with them. One of the more typical examples is that of a pizza builder. Here's an example, without a Fluent Interface:

PizzaBuilder builder = new PizzaBuilder();
builder.setDiameter(12);
builder.setBase(Base.STONEBAKED);
builder.addTopping(cheese);
builder.addTopping(tomato);

Pizza pizza = builder.build();

This feels awkward, it doesn't really seem to be helping that much. Even if we assume Pizza to be immutable it doesn't seem that much improved over assigning the component parts directly to local variables. Trying the same example with a Fluent Interface, we end up with this:

Pizza pizza = aPizza()
    .ofDiameter(12)
    .with(Base.STONEBAKED)
    .with(cheese)
    .with(tomato)
    .build();

Functionally the builder is the same, but I immediately find the example much easier to read. This of course is the purpose of a Fluent Interface, to improve readability. It wasn't until I encountered builders using a Fluent Interface that I started to use them in any great number.

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+Share on RedditEmail this to someone
Posted in Simple Thoughts
0 comments on “Builders with a Fluent Interface
1 Pings/Trackbacks for "Builders with a Fluent Interface"
  1. […] from concrete implementations. Builders make our code more readable, especially when used with a fluent interface. Builders make our code more cohesive, particularly when creating complex objects. The Builder […]