【问题标题】:Java Method Chaining Optionally based on argumentsJava 方法链接 可选地基于参数
【发布时间】:2020-04-27 22:27:45
【问题描述】:

如果第 3 方在方法中请求参数 attachments,我知道我的参数可能为空,如何避免使用 if 并中断方法链接?该方法的定义如下。

// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);

当附件 == null 时,我更喜欢 NOT 为 .withAttachments 使用 if 条件。我知道 javascript 有方法?(),但是什么适合 java8 或更高版本?在(附件== null)的情况下,我根本不想打电话给.withAttachments()。但是,我没有看到类似 javascript 或 typescript 中的 methodA?() 的语法。

return emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses)
  .withAttachments(attachments) // This is conditional...based on attachments
  .withHeader("X-showheader", email.getShowHeader());
  .build();

我需要这样做吗?

EmailBuilder eb = emailBuilder()
  .withSubject(email.getSubject())
  .withReplyTo(replyAddresses);
  if(attachments)
    eb = eb.withAttachments(attachments); // This is conditional...based on attachments
  eb = eb.withHeader("X-showheader", email.getHeader())
  .build;
return eb;

【问题讨论】:

    标签: java optional method-chaining notnull


    【解决方案1】:

    如果withAttachments() 不允许null 值,那么是的,您需要if (attachments != null)。

    但是,由于构建器(通常)不需要特定的方法调用顺序,您可以稍微清理一下代码。

    EmailBuilder eb = emailBuilder()
            .withSubject(email.getSubject())
            .withReplyTo(replyAddresses)
            .withHeader("X-showheader", email.getHeader());
    if (attachments != null)
        eb.withAttachments(attachments);
    return eb.build();
    

    【讨论】:

    • 你是对的。忘记格式化我的评论。我发表了一条新评论。
    • 在使用kotlin时,也可以使用attachments?.let{ eb.withAttachments(this) }
    • 这些都是很好的答案。我选择了下面的答案,因为我只在这个项目中使用 Java,虽然我很欣赏将方法移到底部的注释,但下面的答案确实像我希望的那样删除了 IF。
    【解决方案2】:

    我假设您不能更改 withAttachments 的合同以忽略 null 调用?您可以在Optional 中上游包装附件,然后为orElse 提供一个空的但不为空的impl,无论attachments 是什么类型,例如(假设attachments 是List):

    Optional<...> optionalAttachments = Optional.ofNullable(attachments);
    
    ...
    
    .withAttachments(optionalAttachments.orElse(Collections.emptyList())
    

    更新(基于评论的输入,给安德烈亚斯的小费)

    您也可以使用三元组来实现此目的,例如:

    .withAttachments(attachments != null ? attachments : Collections.emptyList())
    

    【讨论】:

    • 不要使用Optional,而是使用三元运算符:.withAttachments(attachments != null ? attachments : Collections.emptyList()),尽管您可能需要使用Collections.&lt;Attachment&gt;emptyList() 来提示它
    • 谢谢你,@Andreas
    • 谢谢。我很欣赏三元运算符。最初的问题缺少该方法包含 @NotNull 注释的事实,但这仍然有效。
    猜你喜欢
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2015-07-15
    相关资源
    最近更新 更多