News for hackers. Stuff that matters.
Re:Overhead of Returning Optional Values in Java and Rust by shawnz on Saturday October 16, 2021 @01:09PM (#28889350)
Using "Optional" doesn't provide any extra compile-time guarantees except that the function could return Optional.empty(). It's already possible to see that it could return null, so there's no extra guarantees there. The only advantage of "Optional" is that it lets you deal with the empty/null case with a nice functional API instead of if statements. It doesn't do anything to solve the reverse problem of guaranteeing that non-Optional functions can't return null.

If you just want to provide a hint to the caller at compile time about whether you intend for the possibility of returning null, you could use @Nullable/@NotNull annotations to achieve that with no overhead.

Re:Overhead of Returning Optional Values in Java and Rust by ubercow13 on Saturday October 16, 2021 @01:10PM (#28889368)
Yes, in a language like Java where it's retrofitted in years after the decision was already made to allow literally everything to be null. In other languages, that doesn't apply.
Re:Overhead of Returning Optional Values in Java and Rust by brabel on Saturday October 16, 2021 @01:44PM (#28889742)
It doesn't apply in other languages either as long as their nulls are "safe", as in Kotlin or TypeScript.
Re:Overhead of Returning Optional Values in Java and Rust by Zababa on Saturday October 16, 2021 @01:58PM (#28889897)
The thing is that people usually don't have a lot of code to handle the null case, so having optional where you can easily chain the happy case often offers a better experience. It also allows you to differentiate when people will return null for nothing, or when they will return an empty object. I know that in the codebase I work with, people use both. With Optional, you don't have that problem.
Re:Overhead of Returning Optional Values in Java and Rust by shawnz on Saturday October 16, 2021 @05:03PM (#28891485)
Why not just chain the happy case by ignoring nulls, and let any potential NullPointerException bubble up to the point in the code where you would have had an "Optional.orElse" or whatever? Isn't that often just as easy? If you want it to be explicit then you could just add "@throws NullPointerException" to your javadoc. And of course having Optional in your type signature doesn't guarantee you'll never return empty objects (or even null).
Re:Overhead of Returning Optional Values in Java and Rust by valenterry on Saturday October 16, 2021 @09:36PM (#28893217)
Because then you cannot differentiate anymore between "NullPointerException as a bug" or "NullPointerException as a feature".

E.g. you might want to return the streetnumber of a user's address. When a NPE is thrown, was it because there is a bug somewhere in the code or because the user's address has no street number?

With Optional, it is clear: there was no street number.