hon*_*ute 2 java optional java-8
我习惯用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();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我正在阅读Java 8的可选参数,并注意到我们可以改为执行以下操作:
Optional.ofNullable(file1).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(file2).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(another_param).orElseThrow(NullPointerException::new);
...
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,第二种方法是否有任何弊端,我觉得它对我来说看起来更干净一些。
为了进行输入验证,请改用Objects.requireNonNull:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
Objects.requireNonNull(file1);
Objects.requireNonNull(file2, "custom message");
}
Run Code Online (Sandbox Code Playgroud)
它更简洁,更清楚地传达意图,并且不会创建其他Optional对象。它会抛出一个NullPointerException。
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |