Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Optionals to check input parameters

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.

like image 875
lion_bash Avatar asked Jun 17 '26 19:06

lion_bash


1 Answers

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.

like image 56
Hulk Avatar answered Jun 20 '26 07:06

Hulk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!