[英]is there a more elegant way to code this builder?
這是我的片段
WebClient webClient;
if (logger.isDebugEnabled()) {
webClient = WebClient.builder() //
.baseUrl(eprBaseUrl) //
.codecs(codecConfigurer -> {
codecConfigurer.defaultCodecs().jackson2JsonEncoder(loggingEncoder);
}) //
.build();
} else {
webClient = WebClient.builder() //
.baseUrl(eprBaseUrl) //
.build();
}
我的問題很快就暴露了:有沒有更好/更有效的方法來編寫沒有條件塊的這個塊(if/else)
提前感謝
您可以像這樣提取相關部分:
WebClient.Builder webClientBuilder = WebClient.builder().baseUrl(eprBaseUrl);
if (logger.isDebugEnabled()) {
webClientBuilder.codecs(codecConfigurer -> {
codecConfigurer.defaultCodecs().jackson2JsonEncoder(loggingEncoder);
});
}
WebClient webClient = webClientBuilder.build();
您可以初始化您的構建器,直到 if 塊並將 only.codecs 設置為 if 部分:
WebClient.Builder webClientBuilder = WebClient.builder();
if (logger.isDebugEnabled()) {
webClientBuilder
.codecs(codecConfigurer -> {
codecConfigurer.defaultCodecs().jackson2JsonEncoder(loggingEncoder);
});
}
webClientBuilder
.baseUrl(eprBaseUrl)
.build();
然后分支通過調用一個額外的codecs
方法與else不同。 這驅動可用選項:
如果您想保留單個表達式,請檢查null
是否可以傳遞給codecs
。 如果是,則使用條件表達式作為codecs
的參數:
.codecs(logger.isDebugEnabled()? /*logging codec*/: null)
如果你很高興沒有單一的表達或第一個選項是不可能的,你仍然可以提取額外的部分並將共同的部分放在一起:
WebClient.Builder builder = WebClient.builder() //.baseUrl(eprBaseUrl); if(logger.isDebugEnabled()) builder.codecs(/*logging codec*/); webClient = builder.build();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.