我习惯于使用方法顶部的java样板检查输入参数:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
if (file1 == null || file2 == null || file3 == null ||...) {
throw new IllegalArgumentException();
}
if (another_param == null) {
throw new NullPointerException();
}
}
然而,我正在阅读Java 8的选项,并注意到我们可以这样做:
Optional.ofNullable(file1).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(file2).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(another_param).orElseThrow(NullPointerException::new);
...
所以我的问题是,第二种方式有没有什么不好的地方,我觉得它看起来更干净一些。
发布于 2019-06-19 14:09:09
对于输入验证,请改用Objects.requireNonNull:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
Objects.requireNonNull(file1);
Objects.requireNonNull(file2, "custom message");
}
它更简洁,更清楚地传达意图,并且不创建额外的Optional
对象。不过,它抛出了一个NullPointerException
。
发布于 2019-06-19 14:12:00
这样做没有缺点,代码也会工作得很好,但Optional是为了服务于不同的purpose.For示例而引入的,您可以在接口的方法签名中使用Optional,以便清楚地告诉您的客户,您的方法返回的值是“可选的”.This,这样您的客户就不必进行猜测工作了。
发布于 2019-06-19 14:08:07
不,第二种方式没有负面影响。两者做同样的事情,但以不同的方式。Optional
是Java8中添加的一个新特性。
https://stackoverflow.com/questions/56660967
复制相似问题