firstpostcommenter firstpostcommenter - 3 months ago 17
Java Question

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

I am not sure if this is a duplicate question.

I have a Java method with 4 return statements, Each return statement is returning a different HTTP status.

How to fix this checkstyle error to reduce the return statements.

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

Answer

You can define an HttpStatus and then use just a single return statement:

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

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