假设我们有一个像这样的 if 语句:
public A save(A a) {
if (isValid.test(a)) {
return aRepository.save(a);
}
throw new ANotValidException("A is not valid");
}
isValid
是一个谓词,它可能看起来像:
private Predicate<A> isValid = (a) -> (a != null);
你觉得怎么样?我可以以某种方式让它更干净吗?
我的意思是,例如使用 Optional
将其减少为 1 行,并使用 .orElseThrow();
最佳答案
使用可选
和抛出
自定义异常
的更精确版本应为:
public A save(A a) throws ANotValidException { // throws the custom exception
return Optional.ofNullable(a) // since your predicate is to check for not null
.map(aRepository::save)
.orElseThrow(() -> new ANotValidException(a + "A is not valid"));
}
关于java - 重写 if 语句,以更简洁的方式抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54652750/