Builder Pattern – Why is the Builder Pattern Often Implemented Like This?

builder-patterndesign-patterns

Often I see the implementation of the builder pattern (in Java) to be like this:

public class Foo {
    private Foo(FooBuilder builder) {
        // get alle the parameters from the builder and apply them to this instance
    }

    public static class FooBuilder {
        // ...
        public Foo build() {
            return new Foo(this); // <- this part is what irritates me
        }
    }
}

Examples also here:

Why do people introduce the strong (mutual) dependency between builder and type to build?

EDIT: I mean, I know that by its nature the builder is tied to the class I want to build an instance from (FooBuilder -> Foo). What I questioning is: why is there the necessity for the other way around (Foo -> FooBuilder)

On the contrary I see (less often) implementations that create a new instace of Foo when the builder is created and set the fields on the instance of Foo when the appropriate builder-methods are called. I like this approach better, because it still has a fluent API and does not tie the class to its builder. Is there any downside of this other approach?

Best Answer

It boils down to never having a Foo in a half constructed state

Some reasons that spring to mind:

The builder's is by nature tied to the class it is constructing. You can think of the intermediate states of the builder as partial application of the constructor, so your argument that it is too coupled isn't persuasive.

By passing the whole builder in, fields in MyClass can be final, making reasoning about MyClass easier. If the fields are not final, you could just as easily have fluent setters than a builder.

Related Topic