[英]Java Method Chaining Optionally based on arguments
如果第 3 方請求方法中的參數attachments
,知道我的參數可能是 null,我如何避免使用if
和 break 方法鏈接? 該方法具有以下定義。
// import org.jetbrains.annotations.NotNull;
EmailBuilder withAttachments(@NotNull List<Attachment> attachments);
當附件 == null 時,我寧願不使用 if 條件 for.withAttachments。我知道 javascript 有方法?(),但是什么適合 java8 或更高版本? 在 (attachments == null) 的情況下,我根本不想調用.withAttachments()
。 但是,我沒有看到與 methodA?() 類似的語法,例如 javascript 或 typescript。
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
的 impl,例如(假設attachments
是List
):
Optional<...> optionalAttachments = Optional.ofNullable(attachments);
...
.withAttachments(optionalAttachments.orElse(Collections.emptyList())
更新(基於評論的輸入,給安德烈亞斯的帽子提示)
您也可以使用三元組來實現這一點,例如:
.withAttachments(attachments != null ? attachments : Collections.emptyList())
如果您可以編輯或擴展構建器,則可以使用以下方法。
public class ChainBuilder {
public ChainBuilder ifApplicable(
Supplier<Boolean> filter,
Consumer<ChainBuilder> extension) {
if (filter.get()) {
extension.accept(this);
}
return this;
}
public ChainBuilder withAttribute1(String attribute1) {
//handle store attribute1;
return this;
}
public ChainBuilder withAttribute2(String attribute2) {
//handle store attribute2;
return this;
}
public SomeData build() {
return new SomeDate(); //with the optional attributes
}
}
客戶端代碼可以鏈接這些方法:
SomeData data = new ChainBuilder()
.withAttribute1("A")
.ifApplicable(() -> false, builder -> builder.withAttribute2("B"))
.build();
這只是一個例子。 如果您有多個條件,將其包含到構建器 class 中可能是有意義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.