Deprecate @Nonnull and @Nullable using Optional
If used correctly, Optional in Java makes @Nullable and @Nonnull annotations obsolete.
What Is Optional
Java 8 introduced a class called Optional. The intention is to solve the problem of null reference as a method parameter and as a returned value.
The recommendation is to use Optional.empty() instead of null. For example, a person may or may not have a title because of which the following method can return null:
public @Nullable String getTitle() {
return this.title;
}
With the introduction of Optional, this method should be written as:
public Optional<String> getTitle() {
return Optional.ofNullable(this.title);
}
The caller of this method knows that the returned value may or may not be present and can handle both the cases appropriately.
Similarly, use Optional as a method parameter for values that may or may not be present. For example:
public Long total(@Nonnull Long bill, @Nullable Long tip) {
return bill + (tip == null ? 0l : tip);
}
should be written as:
public Long total(Long bill, Optional<Long> tip) {
return bill + tip.orElse(0l);
}
Use Optional And Remove The Null Checks
As you can see in the examples above, if Optional is used correctly then there is no need to perform a null check on any method parameter or any returned value. That is because:
- All the method parameters and all the returned values are referencing a not null value.
- If a parameter value or a returned value is not present then empty Optional is used (a non-null reference).
Remove The Annotations
So, if everything is not null then what is the use of @Nullable annotation? And if everything is not null then @Nonnull annotation is redundant!
My Recommendation
I recommend removing the @Nullable and @Nonnull annotations from the codebase. Let the data type define the intention instead of some annotation which can be forgotten and has a limited capability in terms of static analysis and runtime checks.