Java 检查输入参数的选项
Java Optionals to check input parameters
我正在使用方法顶部的 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);
...
所以我的问题是第二种方式有什么缺点吗,我觉得它看起来更干净一些。
不,采用第二种方式没有任何缺点。两者做同样的事情,但方式不同。 Optional
是 Java 8.
中添加的新功能
对于输入验证,请改用 Objects.requireNonNull:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
Objects.requireNonNull(file1);
Objects.requireNonNull(file2, "custom message");
}
它更简洁,更清楚地传达意图并且不会创建额外的 Optional
对象。不过,它会抛出 NullPointerException
。
这样做没有任何缺点,代码可以正常工作,但是引入了 Optional 来服务不同的 purpose.For 示例,您可以在接口的方法签名中使用 Optional in-order 清楚地告诉您的客户您的方法返回的值是 "Optional"。这样您的客户就不必进行猜测了。
我正在使用方法顶部的 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);
...
所以我的问题是第二种方式有什么缺点吗,我觉得它看起来更干净一些。
不,采用第二种方式没有任何缺点。两者做同样的事情,但方式不同。 Optional
是 Java 8.
对于输入验证,请改用 Objects.requireNonNull:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
Objects.requireNonNull(file1);
Objects.requireNonNull(file2, "custom message");
}
它更简洁,更清楚地传达意图并且不会创建额外的 Optional
对象。不过,它会抛出 NullPointerException
。
这样做没有任何缺点,代码可以正常工作,但是引入了 Optional 来服务不同的 purpose.For 示例,您可以在接口的方法签名中使用 Optional in-order 清楚地告诉您的客户您的方法返回的值是 "Optional"。这样您的客户就不必进行猜测了。