nullness basic model
This page gives the most basic understanding of JSpecify nullness annotations. We hope it should be enough for you to get started, and handle most situations acceptably. You can always move on to the type system model when ready.
1. What Java does:
- Wherever references can flow through a program, there's a type there, restricting which references are allowed through. Unfortunately, it always allows
null
!
2 What JSpecify does:
- In those places, I can add a simple extra bit of related information: "and is
null
okay here?"
3. What my tool does:
- It uses that information in "various smart ways" to discover potential bugs: places where
null
might flow unpermitted, and places that might try to dereferencenull
and trigger aNullPointerException
.
4. What I do:
I might:
- correct the annotations wherever that reference came from
- correct the annotations wherever it's going to
- fix this code itself handle the null case in some way (such as using
requireNonNull()
) - or if it really seems safe, I might just add
@SuppressWarnings
To do my part of that, I just think through where I do or don't want null
to be allowed to flow in my program, then follow some basic recipes:
- I mark my classes/packages/modules with
@NullMarked
. - If a parameter is sometimes willing to accept
null
, I mark it nullable. - If a method might sometimes return
null
, I mark its return type nullable. - When I use a generic class like
List<T>
:- If I want to treat every unannotated
T
in that class as nullable all at once, I writeList<@Nullable Foo>
.
- If I want to treat every unannotated
- When I write a generic class like
class MyList<T>
:- If I'd like its users to have that option (just discussed in the previous bullet), I write
class List<T extends @Nullable Object>
.
- If I'd like its users to have that option (just discussed in the previous bullet), I write
(TODO: we can fill this out a little bit more.)
If I hit a case where the Basic Model falls short, or I just crave a deeper understanding of those "various smart things" my tool is doing, it's time to read the type system model.
Note: The contents of this wiki are not final, and represent current thinking and discussions.