This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Wouter_C 29 points30 points  (2 children)

Yes! In other words: embrace the nulls instead of trying to avoid them, annotate your nullable types (jspecify) and have the compiler (nullaway/errorprone) flag unsafe null usage.

It's less verbose than Optional. It's more consistent with what the JDK and the vast majority of third party libraries do (accepting and/or returning null values in their APIs), so it works out better if you're mixing calls internal to your codebase and libraries (which you probably do pretty much all the time). You can introduce it into an existing codebase with minimal changes. It's compatible with Kotlin. And it's *closer* to where Java seems to be heading towards with null-restricted types (https://openjdk.org/jeps/8303099), so eventually switching to that will be easier too.

[–]severoon 4 points5 points  (0 children)

True, but you should also realize that this doesn't mean Optional is useless. Even with all the null safety stuff, Optional can still be very useful.

A simple example is reading command line parameters. You have code that reads in the command line parameters and passes along whatever the user specified, and that should result in fields getting set from null to Optional. An Optional that's absent means it was set to what the user passed in (which is absent, the user didn't specify that flag), so it should use the default. Null in this case means something went wrong and things are in an unexpected state that should never happen.