We are using the builder pattern to create some input for service, and it looks like something like this (simplified):
final SomeInput input = SomeInput.builder()
.withSomeId(....)
.withSomeState(....)
...
.build();
There's some attribute that we want to set in SomeInput, but only if it is present. So after creating the object, I do something like this:
Optional<String> secondaryId = infoProvider.getSecondaryId();
if (secondaryId.isPresent()) {
input.setSecondaryId(secondaryId.get());
}
I was wondering:
a) Is there a better/cleaner way to do this? b) If I do need to do it this way, can I avoid the "if" statement and utilize some functionality with Optional?
(Note: I cannot change the builder itself, and I cannot that the secondaryId is a String, but that what we retrieve from infoProvider is an optional)
Builder pattern aims to “Separate the construction of a complex object from its representation so that the same construction process can create different representations.” It is used to construct a complex object step by step and the final step will return the object.
Advantages of the Builder pattern include: Allows you to vary a product's internal representation. Encapsulates code for construction and representation. Provides control over steps of construction process.
The build() method in Stream. Builder class is used to build the stream. It returns the built stream. The syntax is as follows: Stream<T>l build() Import the following package for the Stream.Builder class in Java: import java.
You can create an Optional object using the of() method, which will return an Optional object containing the given value if the value is non-null, or an empty Optional object if the value is null.
A little bit cleaner would be to use ifPresent
secondaryId.ifPresent(input::setSecondaryId);
but that's pretty much the best you can get with these requirements.
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