Add nullability annotations to main API and extension points #215
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds nullability annotations (JSR 305) to the main API and extension points. For conciseness and safety, the annotations are not comprehensive. There is a lot of room to continue annotating, but in this PR I have selected the methods that are likely to have a bigger impact.
These annotations provide a richer API contract that allows compilers, IDEs and static analysis tools to do a better job at helping developers and preventing bugs.
For example, before this PR, if a developer wanted to implement a new
Gen
in Kotlin, the IDE would automatically generate the following skeleton:The question marks after the parameter types indicate that the parameters are nullable, because the IDE does not know better and makes the safest choice on behalf of the developer (this is called a "platform type" in Kotlin). The developer then has two choices:
With the changes in this PR, the two parameters are now annotated with
@Nonnull
in the interface. The IDE will generate the following skeleton:Note the absence of question marks. The developer does not need to be defensive and handle a hypothetical null, and the type checker can guarantee that the implementation of the method is NPE-free.
The drawback of this change is that it may cause compilation errors in some applications. Going back to the first example, if the developer decided to keep the question marks, this PR will cause a compilation error, because the
generate
method in the application no longer overrides thegenerate
method in the interface (they have different signatures). The fix is simple: just remove the question marks to match the signature of the interface. This problem may affect some Kotlin users, and potentially also Java applications using static analysis tools like Findbugs.