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?
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.
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.
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