3 ms·
> Optional<T> myOptional = null That hasn't been a problem for me in practice. It's pretty clear that a reference to Optional should never be null. It can be s
by jcrites 11y ago
> Optional<T> myOptional = null
That hasn't been a problem for me in practice. It's pretty clear that a reference to Optional should never be null. It can be statically or dynamically checked with @Nonnull or a precondition.
> but the same was true for nullable properties.
It's inconvenient to have to treat everything as possibly null. It's a lot nicer to create the convention, within one's codebase, that references are always nonnull and only Optional are nullable.
- gurkendoktor 11y ago> That hasn't been a problem for me in practice. It has for me. Functions have multiple return points, some of them returning "null". Lead developer insists we use Optional<> to clarify that these functions can return null. People go over the function, replacing each instance of "return null" with "return Optional.empty()", but forget some instances. Now we have Optionals that are sometimes null.
- RHSeeger 11y agoBut that's a bug in the library (or code you're calling into), not a bug in how you're using it. That's the main difference in my opinion. Optional allows the code to say "I never intend to return null, only an Optional that may be nothing". In theory, a library/module/whatever that's been converted to use Optional should not have any calls that do return null. In theory, its no different than a C API that can return a size or -1 for failure. Sure, it could return -2 because the language allows it, but you shouldn't need to check for that in your code that uses it.
- jcrites 11y agoIf you are in the midst of an upgrade like this, then you might want to program defensively. In this case I would do that by applying annotations like FindBugs' @CheckForNull or @Nonnull or @Nullable. Across a trust boundary like an interface, it's possible to establish a convention like: every reference shall have one of those. You might be able to write a CheckStyle rule that verifies that every reference either has an annotation or is an Optional. Last but not least, assertions can be tremendously useful. Add Objects.requireNonNull() checks liberally, especially anywhere you pass a reference from one place to another without using it. By applying these techniques you can quickly create a "demilitarized zone" for null, allowing you to use Optional confidently on the other side. Errors are caught quickly and locally by analysis and assertions. In a large codebase it's not an all at once upgrade, unless you refactor checked by static analysis, but you can be confident in the parts you've upgraded.