Я пытаюсь объединить 8 одинаковых критериев для простого запроса.
Я написал метод, подобный приведенному выше
private Specification<CustomerHeaderParameter> buildCustomerHeaderParameterSpecifications(String status, String customerType, Integer segment, String module, String cardType, String processType, String rewardType, Integer intervalMin, Integer intervalMax) {
Specification<CustomerHeaderParameter> result = Specification.where(withStatus(StatusCode.getEnum(status)));
if (!StringUtils.isEmpty(customerType)) result.and(withCustomerType(CustomerType.getEnum(cardType)));
if (segment != null) result.and(withSegment(SegmentParameterNumber.valueOf(segment)));
if (!StringUtils.isEmpty(module)) result.and(withModule(ModuleType.valueOf(module)));
if (!StringUtils.isEmpty(cardType)) result.and(withCardType(CardType.getEnum(cardType)));
if (!StringUtils.isEmpty(processType)) result.and(withProcessType(ProcessType.valueOf(processType)));
if (!StringUtils.isEmpty(rewardType)) result.and(withRewardType(RewardType.valueOf(rewardType)));
if (intervalMin != null && intervalMax != null) result.and(inInterval(intervalMin, intervalMax));
return result;
}
Но здесь первая строка может вызвать NullPointerException или IllegalArgumentException, если status имеет значение null или отличаются от значений enum, потому что все мои классы Enum похожи на
public enum StatusCode {
ACTIVE("A"), PASSIVE("P");
private String value;
StatusCode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static StatusCode getEnum(String value) {
return Arrays.stream(values()).filter(v -> v.getValue().equalsIgnoreCase(value)).findFirst().orElseThrow(IllegalArgumentException::new);
}
}
, а мои методы stati c похожи на
static Specification<CustomerHeaderParameter> withStatus(StatusCode status) {
return (param, cq, cb) -> cb.equal(param.get(STATUS_CODE), status);
}
Как можно предотвратить исключения, если параметры метода нулевые или отличаются от значений в моих перечислениях?
Или общий вопрос; Какова наилучшая практика объединения спецификаций?