[如果第三方在方法中请求参数attachments
,我知道我的参数可能为空,如何避免使用if
和中断方法链接?该方法具有以下定义。
// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);
我希望NOT使用.withAttachments的if条件,当附件== null时。我知道javascript具有method?(),但是什么适用于java8或更高版本?在(附件== null)的情况下,我根本不想调用.withAttachments()
。但是,在JavaScript或打字稿中,我看不到语法可与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;
如果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();
我假设您无法更改withAttachments
的合同以忽略具有null的呼叫?您可以在Optional
中上游包装附件,然后为orElse
提供一个空的但不为null的attachments
类型的隐含内容,例如(假设attachments
是List
):
Optional<...> optionalAttachments = Optional.ofNullable(attachments);
...
.withAttachments(optionalAttachments.orElse(Collections.emptyList())
UPDATE(基于来自评论的提示,给安德里亚斯的建议)
您也可以通过三元来实现,例如:
.withAttachments(attachments != null ? attachments : Collections.emptyList())