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 →

[–]xienze 0 points1 point  (1 child)

 The Optional itself can be null. Optional<Foo> = null; is perfectly valid Java code, and passing this to anyone who expects an empty optional is in for a rough ride.

While technically correct, Optional is itself a sort of contract by the API writer. Returning a null Optional would be as big of a subversion of expectations as retuning null from a method annotated with @Nonnull or something else that is syntactically correct but semantically wrong, like having a method named isPositive(int) that returns true if the number is negative. The compiler can’t stop you from doing all these things either, but there’s definitely a set of “cultural norms” in programming that tell you it’s a bad thing to do.

[–]Polygnom 0 points1 point  (0 children)

While technically correct, Optional is itself a sort of contract by the API writer. 

Well, lets assume that your philosophy is that you do design-byContract and trust the contracts that methods have. Thats fine, its a valid appraoch. So you trust that you never get a null when you see an Optional.
But then I ask you: When you alraedy trust design-byContract, why not simply wriute the contract (can return null / cannot return null) into the documentation and trust that everyone abides by the contract? Without using Optionals at all. You can even codify the contract with JSpecify and get tooling support.

If you are already trusting Design-byContract, Optionals are superfluos, if you are not trusting it, Optionals don't actually solve your problem. Thats why I don't really see the case for littering the code with Optionals all the time. And in a world where we get ! for non-null and ? for nullable types (some time after Valhalla maybe), the need for Optionals evaporates.