Hacker News new | ask | show | jobs
by premium-concern 3530 days ago
That's an extremely weak argument. Java's Optional is broken and should never be used.
2 comments

If that is true, then it's another example supporting my point.
No. Java messing things up as usual, doesn't have any broader impact on the usefulness of the concept.

Error handling with null is wrong and broken, regardless of whether the null is "typed" or not.

null might have some very limited other uses, but they will never compete with those structures designed for error handling, because they do something fundamentally different.

My argument is practical, not theoretical. Platitudes and ideals are disposable when you have to actually build something.
Yawn.

Java is the platform with NPEs and null checks everywhere. If that's your definition of practical, sure, go ahead.

Could you expand on this?
Optional#map is implemented incorrectly.

   someOptional.map(a).map(b) NOT EQUAL TO someOptional.map(a.andThen(b)
Ah, that's unfortunate.

Because of the order in which side effects occur, or is there something else as well? (I haven't Javaed in anger since before Optional).

Consider two functions (excuse my Scala):

  scala> val str: Function[String, String] = s => if (s.length > 3) s else null
  str: java.util.function.Function[String,String] = $$Lambda$1369/859456754@2c668c2a

  scala> val num: Function[String, Integer] = s => if (s == null) -1 else s.length
  num: java.util.function.Function[String,Integer] = $$Lambda$1376/1887041776@121cf6f4
With Optional, you receive different results depending on whether you call map twice, or combine the functions first:

  scala> Optional.of("Foo").map[String](str).map[Integer](num)
  res12: java.util.Optional[Integer] = Optional.empty

  scala> Optional.of("Foo").map[Integer](str.andThen(num))
  res15: java.util.Optional[Integer] = Optional[-1]
This is incorrect. (They decided to disallow null as Optional's value for whatever insane reason.)

It also leads to all sort of weird usability issues: The old "`someMap.get(...)` returned null ... now does that mean the entry doesn't exist, or the entry exists and it is null?"

In fact they are currently working on special hacks to Java 10's Generics, because they realized that important collection classes don't work well with specialization, and even their new Optional can't save them. (Not directly related, but a good example how design mistakes combine and cause even more pain down the road.)

Interesting, thanks!