Consider the following POJO with a compound key, keyA and keyB, some values, and a lombok builder annotation.
@Builder
class Foo {
int keyA;
int keyB;
String author;
String value;
... other stuff
}
With the traditional builder paradigm, you would just chain all the builder elements together.
List<Foo> list = new ArrayList<>();
list.add(Foo.builder().keyA(1234).keyB(1).author("Bob Jones").value(...).build());
list.add(Foo.builder().keyA(1234).keyB(3).author("Bob Jones").value(...).build());
list.add(Foo.builder().keyA(1234).keyB(4).author("Bob Jones").value(...).build());
list.add(Foo.builder().keyA(1234).keyB(5).author("Bob Jones").value(...).build());
list.add(Foo.builder().keyA(1234).keyB(7).author("Bob Jones").value(...).build());
Instead, I could save the builder as a variable and reuse it, overwriting only certain values.
List<Foo> list = new ArrayList<>();
Foo.FooBuilder builder = Foo.builder().keyA(1234).author("Bob Jones");
list.add(builder.keyB(1).value(...).build());
list.add(builder.keyB(3).value(...).build());
list.add(builder.keyB(4).value(...).build());
list.add(builder.keyB(5).value(...).build());
list.add(builder.keyB(7).value(...).build());
The builder values are overwritten between each build call, and a new object is created on build()
.
Now, these lines are not that too different in complexity, but as larger objects get created, with canned values being consistent across many of them, the code becomes significantly harder to manage because you have to update every builder statement if each of them requires a base change.
Assuming you only pass references and update values, is this an appropriate use of the builder paradigm, or is the concept of builder paradigm strictly one builder yields one object?
It's always appropriate to use the same builder to create multiple objects. After all, that's the basic purpose of builder, to build objects.
The way you used the builder is completely acceptable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With