I am using to checking input parameters with the java boilerplate like this on the top of the method:
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();
}
}
However, I was reading up on Java 8's optionals and noticed we could do something like this instead:
Optional.ofNullable(file1).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(file2).orElseThrow(IllegalArgumentException::new);
Optional.ofNullable(another_param).orElseThrow(NullPointerException::new);
...
So my question is is there any downside of doing it the second way, I feel that it looks a bit cleaner to me.
For input validation, use Objects.requireNonNull instead:
public static Boolean filesExist(String file1, String file2, String file3 ... ) {
Objects.requireNonNull(file1);
Objects.requireNonNull(file2, "custom message");
}
It is more concise, communicates intention more clearly and does not create an additional Optional object. It throws a NullPointerException, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With