Skip to content

Conversation

@wheata03
Copy link

@wheata03 wheata03 commented Apr 3, 2024

When you have a long builder sequence, it is sometimes helpful to insert logic into the pipeline to avoid having to step out of the builder to conditionally add an element.

MPD.Builder b = MPD.builder()
  // lots of builder elements
  .withField();

if (someCondition) {
  // build items when condition applies
  b = b.withSomething()
    .withSomethingElse();
}

return b.withOtherValues()
    .build();

Making use of a java.util.function.Function we can continue the pipeline and add the conditional without the top-level temporary variable:

return MPD.builder()
  // lots of builder elements
  .withField();
  .apply(builder -> {
    if (someCondition) {
      return builder
        .withSomething()
        .withSomethingElse();
    }
    return builder;
  })
  .withOtherValues()
  .build();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant