Home > Enterprise >  Conditionally include/exclude elements in builder
Conditionally include/exclude elements in builder

Time:10-10

I have this bulider method:

public static QuoteDetails quoteDetailsForMA(String response) {
  handleErrors(response);
  try {
    FullResponse quoteDetails = extractResponse(response);
    Summary summary = summaryMA(quoteDetails);
    List<PenaltyElement> penalties = retrievePenalties(quoteDetails);
    return QuoteDetails.builder()
        .priceSummary(summary)
        .penalties(penalties)
        .build();
  } catch (Exception e) {
    LOGGER.error(
        "Exception thrown response: {}",
        e.getMessage());
  }
}

penalties may or may not be an empty list. If it is not empty I wish to execute the return statement as it currently is(with .penalties(penalties). However, If penalties is an empty list I wish to exclude it from my return. E.g. I wish to return this:

return QuoteDetails.builder()
    .priceSummary(summary)
    .build();

Is this possible and if so, how is it done?

CodePudding user response:

The easiest technique is to make the .penalties(penalties) method null and empty list tolerant.

Note, the authors of both of the other answers appear to love NullPointerExceptions.

Here is some example code (with assumptions):

private List<Penalty> penaltiesList;

public QuoteDetailsBuilder penalties(final List<Penalty> newValue)
{
  if (CollectionUtils.isNotEmpty(newValue))
  {
    penaltiesList = newValue;
  }

  return this;
}

CollectionUtils is an apache utility for some null-safe collection functionality.

CodePudding user response:

You can do it via the isEmpty() method to see if it's empty or not:

.penalties(penalties.isEmpty() ? null : penalties)

CodePudding user response:

Two "obvious" solutions come to my mind:

  1. The builder supports an empty list in the correct way. You could maybe implement your own builder to do that which is just a wrapper around the original and doesn't call the original method penalties if the parameter is an empty list.

  2. Use if as you would regularly do for "conditional" handling:

QuoteDetailsBuilder builder  = QuoteDetails.builder()
        .priceSummary(summary);
if ((null != penalties) && !penalties.isEmpty()) {
    builder = builder.penalties(penalties);
}
return builder.build();

(Of course in solution #2 the name of the builder class may vary depending on the implementation.)

  • Related