Search code examples
javabuilder

is there a more elegant way to code this builder?


Here is my snippet:

WebClient webClient;
    if (logger.isDebugEnabled()) {
        webClient = WebClient.builder() //
                .baseUrl(eprBaseUrl) //
                .codecs(codecConfigurer -> {
                    codecConfigurer.defaultCodecs().jackson2JsonEncoder(loggingEncoder);
                }) //
                .build();
    } else {
        webClient = WebClient.builder() //
                .baseUrl(eprBaseUrl) //
                .build();
    }

Is there a better/more efficient way to write this block without condition block (if/else)?


Solution

  • You can extract the relevant part like this:

    WebClient.Builder webClientBuilder = WebClient.builder().baseUrl(eprBaseUrl);
    if (logger.isDebugEnabled()) {
      webClientBuilder.codecs(codecConfigurer -> {
         codecConfigurer.defaultCodecs().jackson2JsonEncoder(loggingEncoder);
      });
    }
    WebClient webClient = webClientBuilder.build();