The many different builder patterns

Created: 2016/05/15 14:38:02+0000 Revised: 2016/05/29 18:12:09+0000 Revisions:  3 2 1

You may have heard of the builder pattern. It's one of the Gang of Four's original design patterns. A builder is an object that provides a method to construct an object and other methods to configure the object to be built. A builder is first configured and then used to construct an object. It sounds simple but there are variants on this pattern.

The builder is often considered a good candidate for a fluent interface. A fluent interface makes the builder object easier to configure. Multiple methods need to be called on the builder to fully configure it, a fluent interface allows them all to be called in a single statement. Subjectivly easier to read by reducing the repetition of the target.

Less commonly addressed are the differences between mutable and immutable builders. Most examples I see are for mutable builders and yet I find myself drawn to the immutable builder. They are just better.

An immutable builder must be fluent or there would be no way to configure the builder. The benefit is improved usability. Once created it can be used as a template to derive slightly different builders from. These builders can be spacial and temporally separated. A mutable builder can only be used in the place it is created because once passed to other places or used over time it stops being something you can trust to create an object the way you just configured it. You can always trust an immutable builder.