简体   繁体   English

有条件地包含/排除构建器中的元素

[英]Conditionally include/exclude elements in builder

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. penalties可能是也可能不是空列表。 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. Eg I wish to return this:如果它不为空,我希望按当前状态执行返回语句(带有.penalties(penalties) penalties但是,如果 penalty 是一个空列表,我希望将其从我的返回中排除。例如,我希望返回这个:

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

Is this possible and if so, how is it done?这可能吗?如果可以,它是如何实现的?

The easiest technique is to make the .penalties(penalties) method null and empty list tolerant.最简单的技术是使.penalties(penalties)方法 null 和空列表容忍。

Note, the authors of both of the other answers appear to love NullPointerExceptions.请注意,其他两个答案的作者似乎都喜欢 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. CollectionUtils是一个 apache 实用程序,用于某些空安全集合功能。

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.您也许可以实现自己的构建器来执行此操作,它只是原始对象的包装器,如果参数为空列表,则不会调用原始方法penalties

  2. Use if as you would regularly do for "conditional" handling:使用if就像你经常做的“条件”处理一样:

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.) (当然,在解决方案 #2 中,构建器的名称 class 可能会因实现而异。)

You can do it via the isEmpty() method to see if it's empty or not:您可以通过isEmpty()方法查看它是否为空:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM