Mikołaj Milej
Mikołaj Milej

Reputation: 38

Builder pattern - Build() method reusability

There is a Builder. Programming language is irrelevant.

Which one is correct:

    • you set up the builder
    • you are able to call Build() as many times you like to. So in result you end up with X objects of the same parameters (or even changed parameters if you add more configuration.
    • you set up the builder
    • after Build() call, the builder has to be set up again to be able build another object.

Is there any convention how should the Build() behave?

Both scenarios may be valid. In first scenario you have to copy the values, in second you are able to move the values from builder to created object.

I'd like to properly name the "builders" to be able to distinguish behaviour by just reading the name; code comments are lies, the code always tells the truth.

=== edit

The solution for C++11 is quite interesting:

class Builder final
{
public:
    Result Build() &&;
    Result Build() & const; //if you allow building multiple times
};

//... usage:
auto optimized = Builder().Build();
auto builder;
auto copy = builder.Build();
auto optimized2 = std::move(builder).Build();

Using variable after std::move is mainly assumed as invalid operation (it's in valid, but not determined state until you set a new state of this variable, or you say in type documentation that it's fine to use it)

Upvotes: 1

Views: 2284

Answers (2)

Ricardo Costeira
Ricardo Costeira

Reputation: 3331

Both ways are valid, with some caveats. It really depends on your purpose. To the outer code, the build method only returns an object of the type that the Builder is responsible for creating. However, internally you can create that object right in the Builder's constructor (when you want different instances of the Builder), or you can create the object directly inside the build method (I've seen a lot of a static Builders like this).

Through the first option, build() always returns a reference to the same object. Through the second one, you get a completely new object every time you call build().

Note, however, that the pattern is flexible enough to do things the other way around - create a new object on every build call on a Builder instance, and reuse the same (static) object on a static Builder.

Like I said at the beginning, both forms are valid. It really depends on your domain and purpose.

Upvotes: 0

jaco0646
jaco0646

Reputation: 17074

Josh Bloch describes it the first way in Effective Java.

The Builder pattern is quite flexible. A single builder can be used repeatedly to build multiple objects. The parameters of the builder can be tweaked between invocations of the build method to vary the objects that are created.

Upvotes: 1

Related Questions