Checkstyle 错误 - Return 计数为 4(允许的最大值为 2)

Checkstyle error - Return count is 4 (max allowed is 2)

我不确定这是否是一个重复的问题。

我有一个包含 4 个 return 语句的 Java 方法,每个 return 语句是 return 不同的 HTTP 状态。

如何修复此检查样式错误以减少 return 语句。

if (condition) {
return new ResponseEntity<Domain>(domain, HttpStatus.CONFLICT);
            } else if (condition2) {
return new ResponseEntity<Domain>(domain, HttpStatus.PRECONDITION_FAILED);
            } else {
return new ResponseEntity<Domain>(domain, HttpStatus.OK);
}

您可以定义一个 HttpStatus,然后只使用一个 return 语句:

HttpStatus status;
if (condition) {
    status = HttpStatus.CONFLICT;
else if (condition2) {
    status = HttpStatus.PRECONDITION_FAILED;
else {
    status = HttpStatus.OK;
}

return new ResponseEntity<Domain>(domain, status);