mpd-tools icon indicating copy to clipboard operation
mpd-tools copied to clipboard

Add 'apply' function to give access to the builder in a build pipeline.

Open wheata03 opened this issue 10 months ago • 0 comments

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();

wheata03 avatar Apr 03 '24 17:04 wheata03