3 ms·
What is wrong with Optionals?
by Pet_Ant 6y ago
What is wrong with Optionals?
- doctor_eval 6y agoOptionals can be null, so dereferencing them can still cause an NPE. Also the syntax is horrible. I know the excuse that they are just meant to be used to wrap the return value of a function that might be null, rather than as a guard against NPEs, but that just means we’ve got a crappy, verbose Optional class ... and NPEs. It was the most half assed attempt to fix the billion dollar mistake [0] anyone could have come up with. It needed syntax and compiler support, not a stupid wrapper class. [0] https://en.m.wikipedia.org/wiki/Tony_Hoare https://en.m.wikipedia.org/wiki/Tony_Hoare
- sk5t 6y agoLikely to be addressed with the ongoing effort for value types. Optional + prudent use of @NotNull annotations can get you most of the way there already in practical terms.
- Pet_Ant 6y agoSorry but of course Optional can be null because of Java’s type system. Objects can be null, Optionals are objects. I’d rather it have been different from the beginning but now that it’s here it’s really not something that should change. Just never let anyone get away with returning a null for an optional... though I can imagine the scenario where in. A framework that might cause it to happen. To have special rules for Optional in Java is the wrong answer for a blue collar language at this level of adoption and age. They said they never want to make a change as big as generics again.
- doctor_eval 6y agoI think you’ve read me out of context. Of course I understand why Optionals can be null, I was just pointing out - literally in defence of Java - something I don’t like. I don’t really get your other arguments. I think the problem has been solved better in other languages including Swift, Kotlin and Rust, and Java could have learned from them, but didn’t. I can’t see why direct language support couldn’t have been added to solve this “billion dollar problem”. Even the Elvis operator would have helped.