Simple Implementation of Fluent Builder — Safe Alternative To Traditional Builder

Sergiy Yevtushenko
The Startup
Published in
4 min readJun 20, 2020

--

The Builder pattern is extremely popular in Java applications. Unfortunately it’s often misunderstood and incorrectly implemented and used which results to run time errors.

So, what to do in cases when object must be built completely and there are no safe defaults for fields (i.e. Builder pattern is not applicable)? In such cases would be very convenient to use Fluent Interface pattern which allows to avoid errors caused by missing field(s). Unfortunately proper implementation of Fluent Interface usually is too verbose to be practical so developers use plain Builder and try to rely on careful testing to avoid runtime errors.

Fortunately for most frequent use case when all fields for the object must be set, there is a simple solution which results to very concise and safe implementation of Builder with fluent interface, which I call Fluent Builder.

Lets assume that we want to create a Fluent Builder for simple bean shown below:

public class SimpleBean {
private final int index;
private final String name;
private SimpleBean(final int index, final String name) {
this.index = index;
this.name = name;
}
}

--

--