Marking an optional member variable as NonNull
An additional point is the creation of a free API. The field is not and should not be part of the API.
What's the difference for you between Optional<Object> obj
and Object obj
in the fields?
Both fields can be annotated with @NotNull
. Annotating a field with @NotNull
will give you the same result as annotating Optional
, but without additional calls like ifPresent()
. If you want Optional
to use chaining to apply operations to a field, you are using Optional
incorrectly. There is no reason to use it Optional
in the field.
You can read more on the openjdk mailing list for an optional discussion .
This option allows you to create a free API mail.openjdk
source to share
Yes, you must mark each variable Optional
as @NonNull
.
An optional variable must never be null. Stuart Marks rules about using optionals start with:
- Never, never, use null for an optional variable or return value.
If you are writing @NonNull
, then you will get help not to break this important rule.
If you don't write @NonNull
, you only have your own personal discipline so that you don't make mistakes, and clients can make mistakes too.
Hence, you should write @NonNull
, which serves as machine readable and machine tested documentation, that a variable should never be null.
This applies not only to fields (member variables), but wherever you use Optional
.
source to share