重写一个以更简洁的方式抛出异常的 if 语句

假设我们有一个这样的 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);

你怎么看?我可以以某种方式使它更清洁吗?我的意思是,例如使用 anOptional将其减少为 1 行.orElseThrow();


慕村225694
浏览 137回答 3
3回答

翻翻过去那场雪

使用Optional和throw定制自定义的更精确版本Exception应为:public A save(A a) throws ANotValidException { // throws the custom exception&nbsp; &nbsp; return Optional.ofNullable(a) // since your predicate is to check for not null&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(aRepository::save)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.orElseThrow(() -> new ANotValidException(a + "A is not valid"));}

青春有我

有人可能会争辩说,以相反的顺序阅读它会更自然,即首先处理验证及其结果,然后继续保存对象。public A save(A a) {&nbsp; &nbsp; if (!isValid.test(a)) {&nbsp; &nbsp; &nbsp; &nbsp; throw new ANotValidException("A is not valid");&nbsp; &nbsp; }&nbsp; &nbsp; return aRepository.save(a);}

拉莫斯之舞

AnOptional可以使代码更具可读性,尤其是在使用谓词对象时:public A save(A a) {&nbsp; &nbsp; return Optional.ofNullable(a)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(isValid)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(aRepository::save)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElseThrow(() -> new ANotValidException("A is not valid"));}您也可以完全摆脱谓词,因为它使用起来很简单Objects::nonNull(除非您的真实谓词测试更复杂)。在这种情况下,保持您当前的状况检查可能更有意义(在我看来)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java