Question

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?

Was it helpful?

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 Splitters.

OTHER TIPS

The latter isn't bad style at all, but it requires that the object can be used right away and then added to one attribute at a time.

In some scenarios, it's preferable to collect all attributes first, and then do a one time creation event, without doing a re-create or update for each additional attribute.

In the sandwich example, the latter is probably fine and there isn't a need for a separate builder class. Maybe a GUI control wants to collect all parameters first and then do a one time create rather than recreate/update for each individual parameter, in which case a separate Builder would be more appropriate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top