Builder Pattern: Why do we need .build()?

builder, design-patterns, java

Solution

One of the greatest advantages of the builder pattern is that its built object can be immutable. With your second example that would either be impossible, assuming `salami()`, `pastrami()`, etc. act as standard setters, or it could be inefficient if they each returned a new instance.

JB Nizet points to Guava's `Splitter`, which is a good example of the latter case. To your point, Guava developers must have felt that "foregoing seemingly unnecessary complication" was enough reason to tolerate a few extra copies during the creation of customized `Splitter`s.

Problem

When researching the builder pattern, the standard pattern is like: ``` new SandwichBuilder().salami().pastrami().cat().build(); ``` Where `.salami(), .pastrami(), and .cat()` return `SandwichBuilders`, and `.build()` returns a `Sandwich`. Is it considered bad style to, instead, use the following convention? ``` new Sandwich().salami().pastrami().cat(); ``` Where `.salami(), .pastrami(), and .cat()` return `Sandwich` directly, foregoing seemingly unnecessary complication?

Original source