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?