Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically throwing IllegalArgumentException when null values are passed to a method

I'm exploring the possibility of eliminating null while refactoring part of a codebase I'm working on. We've upgraded to java 8, so we have Optional<T> at our disposal. In order to do this effectively, we need to make sure null isn't being passed to any of our methods (this is after we wrap any potential null values within Optional that enter our system from external services/libraries). The obvious way to handle this is to explicitly check for null and throw IllegalArgumentException if necessary, however, this would be unreasonably verbose and manual. Is there a less manual/more terse way of doing this?

like image 573
w.brian Avatar asked Dec 02 '22 16:12

w.brian


2 Answers

You can use Objects::requireNonNull for exactly this. For example, in a constructor you can do:

this.myField = Objects.requireNonNull(myField);

It will throw a NullPointerException if you pass null.

Avoid the overuse of Optional. See for example this answer.

like image 105
Paul Boddington Avatar answered Jan 05 '23 00:01

Paul Boddington


You may try Lombok annotation processor which has @NonNull annotation. Annotating the parameter with NonNull will automatically generate the null-check during the compilation, so you will got either NullPointerException or IllegalArgumentException (whichever you like) at runtime.

like image 35
Tagir Valeev Avatar answered Jan 04 '23 22:01

Tagir Valeev