问题描述
我正在使用java8。 我从示例中编写了以下代码。 我想重构它,但是我不知道如何。 如果您有什么好主意,请告诉我。
webClient
.post()
.uri(url)
.header(ACCEPT,APPLICATION_JSON_VALUE)
.body(BodyInserters.fromObject(request))
.exchange()
.flatMap {
clientResponse ->
if (clientResponse.statusCode().is4xxClientError) {
clientResponse.body { clientHttpResponse,_ -> clientHttpResponse.body}
logger.info { "Error Response:"+clientResponse.bodyToMono(String::class.java)}; Mono.error(MyCustomException()))
} else clientResponse.bodyToMono(Person::class.java)
}
解决方法
从“空”检查有效暗示的3位构造一个int
:
int i = (a != "" ? 4 : 0) | (b != "" ? 2 : 0) | (c != "" ? 1 : 0);
(是的,您应该使用equals
或isEmpty()
而不是!=
。这不是重点。)
这将给出一个介于0到7之间的数字。
构造一个由8个元素组成的列表或数组,其中数字是您要返回的值。
然后,使用上方的i
从该列表/数组中选择一个元素:
return list.get(i); // or array[i]
,
您不需要所有这些else
,并且可以使它更加简洁明了:
if(a != "" && b != "" && c != "") return 1;
if(a != "" && b != "") return 2;
if(a != "" && c != "") return 3;
if(b != "" && c != "") return 4;
if(a != "") return 5;
if(b != "") return 6;
if(c != "") return 7;
return 8;