Remix.run Logo
lock1 4 days ago

Unrelated with GP post: What's wrong with Java's Optional?

IIRC it doesn't fulfill monad axiom, but I don't think there's a huge problem with it. By the time you're using Option<>-like, I don't think you should use bare `null` at all in your project. Mixing Option<>-like and bare `null` sounds like playing with fire.

Also, if you're using Java 17+ (`record` in your example), you're probably better off writing your own Option<T> to support sum-type matching & product-type destructuring.

lmm 3 days ago | parent | next [-]

> IIRC it doesn't fulfill monad axiom, but I don't think there's a huge problem with it. By the time you're using Option<>-like, I don't think you should use bare `null` at all in your project. Mixing Option<>-like and bare `null` sounds like playing with fire.

That's completely backwards IME. The whole point of Option is to allow you to make precise distinctions, and not allowing null in it when null is allowed in regular variables is a recipe for disaster.

For example, the flagship use case of Optional is to make it possible to implement something like a safer Map#get(), where you can tell the difference between "value was not in the map" and "value was in the map, but null". A language that wanted to evolve positively could do something like: add Optional to the language, add Map#safeGet that returns Optional, deprecate Map#get, and then one chronic source of bugs would be gone from the language. (And yes, ideally no-one would ever put null in the map and you wouldn't have this problem in the first place - but people do, like it or not). Instead, Java introduced an Optional that you can't put nulls in, so you can't do this.

reverius42 3 days ago | parent [-]

I think they mean, not allowing null outside, and using the None variant of Option to represent a lack of something.

lmm 2 days ago | parent [-]

Removing null completely is a good end goal, but in order to get from there to here we need to migrate trillions of lines of code (and having an option type available is necessary to even get started), and if that option type can't accommodate all the values that are valid in the language and existing codebases (which currently includes null, like it or not) then we can't even get started.

kriops 4 days ago | parent | prev [-]

Optional::map returns an empty optional if the passed function returns null. This is incorrect and can be especially hurtful in intermediate operations. Allowing Optional::map to return an Optional<void> would have been correct.

Alternatively, just don't call it 'map'.

I agree implementing your Option<T> type is better. The problem is that people will use whatever is available in the standard library—I am not working in isolation.