Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way for using builder pattern with optional values?

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)

like image 655
CustardBun Avatar asked Oct 23 '17 18:10

CustardBun


People also ask

When should you use the Builder Pattern?

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.

What is the advantage of builder pattern?

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.

What is .build method in Java?

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.

How do you set the value of an optional object?

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.


1 Answers

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.

like image 51
Kayaman Avatar answered Oct 20 '22 16:10

Kayaman