I am trying to explore the the use of Vavr library within my Java application. I am trying to reduce the if-else ladder using the Vavr library's Match.of() construct.
Here is a piece of code that I have written:
Match(Option.of(clientId)).of(
Case($None(), run(() -> {
metricsService.recordValidationStageMetrics(CLIENT_ID_NOT_PRESENT, type, BLANK);
log.error("Client ID not present in the request header: [{}]", clientId);
throw new ValidationException(EX_REQUEST_CLIENT_ID_EMPTY);
})),
Case($Some($(StringUtils::isBlank)), run(() -> {
metricsService.recordValidationStageMetrics(CLIENT_ID_NOT_PRESENT, type, BLANK);
log.error("Client ID not present in the request header: [{}]", clientId);
throw new ValidationException(EX_REQUEST_CLIENT_ID_EMPTY);
})),
Case($(), run(() -> {
if (isClientIdNotAllowed(clientId)) {
log.error(LOG_CLIENT_ID_NOT_ALLOWED, clientId);
metricsService.recordValidationStageMetrics(CLIENT_ID_NOT_ALLOWED, type, clientId);
throw new ValidationException(EX_ALLOWED_CLIENT_ID_ERROR);
}
}))
);
The problem here is that the Option is always matching the first Case statement. Even if the clientId is non-null, it is validated to None and throws the exception.
So the question is:
- Why is it not behaving in an intended way? What is it that I am missing here?
- Is there a cleaner way to write this?
Actually - as far as I remember - you need to prepend the
runwith() ->which indicates theSuppliervariant of the second argument forCasebeing used. Otherwise it will be evaluated eagerly and hence the firstCasewill be run.The following code works fine:
Try with removing the
() ->and you'll start getting the firstCasebeing matched no matter what the input is.Whether I can be written cleaner. It depends on the version of java you use. I see it as a
switchstatement or pattern matching if the latest is used.