我正在try 探索在Java应用程序中使用Vavr库.我正在try 使用Vavr库的Match.of()
构造减少if-else阶梯.
下面是我编写的一段代码:
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);
}
}))
);
这里的问题是Option
始终与第一条Case
语句匹配.即使clientId
为非null,也会验证为None
并引发异常.
So the question is:
- 为什么它的行为不符合预期?我在这里错过了什么?
- 有没有更干净的方法来写这个?