Declarative syntax for conditional statements

Rajiv thenakliman at gmail.com
Mon Feb 3 11:57:33 UTC 2020


Hi All

I want to introduce a new declarative syntax for conditional statements in
java on the line of streams. I have created a library
https://github.com/thenakliman/if for the same.

It improves the readability of the code. For example if we have following
code


if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new EmployeeServiceException(format(ERROR_MESSAGE,
responseEntity.getStatusCode()));
 } else if (responseEntity.getBody() == null ||
"".equals(responseEntity.getBody().toString())) {
            throw new NoContentException(format(NO_CONTENT_FOUND_MESSAGE,
fromDate, toDate));
 }

 return responseEntity.getBody();

Can be written as

return If.isTrue(responseEntity.getStatusCode() != HttpStatus.OK)
       .thenThrow(() -> new EmployeeServiceException(format(ERROR_MESSAGE,
responseEntity.getStatusCode())))
       .elseIf(responseEntity.getBody() == null)
       .thenThrow(() -> new
NoContentException(format(NO_CONTENT_FOUND_MESSAGE, fromDate, toDate))
       .elseGet((responseEntity) -> responseEntity.getBody())

For more examples, see
https://github.com/thenakliman/if/tree/master/src/test/java/com.thenakliman/ifs

It has multiple syntax, we can keep the one that seems more readable and
concise.

I would like to hear your opinions


More information about the core-libs-dev mailing list