I am curious to know how I can write a shorter version of the following code in Java.
I have the following Java class (belongs to JAX-RS):
I need back the int value of the responseStatus if that's possible (response is not null) otherwise default int status value needs to be returned.
I do not want to add any library dependency to my project just for this small piece of code.
This is the code that came up in my mind first:
private static int getDefaultStatusCodeIfNull(final Response response) {
if (Objects.isNull(response)) {
return Response.Status.INTERNAL_SERVER_ERROR.getStatusCode();
}
return response.getStatus();
}
The following code is maybe shorter with lambda but it is so long and hard to read:
int status = Optional.ofNullable(response)
.orElse(Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()).getStatus();
Is there any shorter one-line way to get this int value?
Do you think the 2nd one is a better solution than the 1st?
Using ternary operator, maybe?
return (response == null) ? Response.Status.INTERNAL_SERVER_ERROR.getStatusCode() : response.getStatus();