重写 if 语句,以更简洁的方式抛出异常
Rewriting an if statement which throws an exception in a cleaner way
假设我们有这样一个 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
将其缩减为带有 .orElseThrow();
的 1 行
Optional
可以使代码更具可读性,尤其是在谓词对象的使用方面:
public A save(A a) {
return Optional.ofNullable(a)
.filter(isValid)
.map(aRepository::save)
.orElseThrow(() -> new ANotValidException("A is not valid"));
}
您也可以完全摆脱谓词,因为它很简单,可以使用 Objects::nonNull
(除非您真正的谓词测试更复杂)。在这种情况下,保持当前状态检查可能更有意义(在我看来)。
有人可能会争辩说,以相反的顺序阅读它会更自然,即首先处理验证及其结果,然后继续保存对象。
public A save(A a) {
if (!isValid.test(a)) {
throw new ANotValidException("A is not valid");
}
return aRepository.save(a);
}
使用 Optional
和 throw
自定义 Exception
的更精确版本应为:
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"));
}
假设我们有这样一个 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
将其缩减为带有 .orElseThrow();
Optional
可以使代码更具可读性,尤其是在谓词对象的使用方面:
public A save(A a) {
return Optional.ofNullable(a)
.filter(isValid)
.map(aRepository::save)
.orElseThrow(() -> new ANotValidException("A is not valid"));
}
您也可以完全摆脱谓词,因为它很简单,可以使用 Objects::nonNull
(除非您真正的谓词测试更复杂)。在这种情况下,保持当前状态检查可能更有意义(在我看来)。
有人可能会争辩说,以相反的顺序阅读它会更自然,即首先处理验证及其结果,然后继续保存对象。
public A save(A a) {
if (!isValid.test(a)) {
throw new ANotValidException("A is not valid");
}
return aRepository.save(a);
}
使用 Optional
和 throw
自定义 Exception
的更精确版本应为:
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"));
}