4 ms·
There are certainly cases where Optional is better than a "this can be null" comment, but consider the possibility that the Map interface was designed to always
by hashmash 5y ago
There are certainly cases where Optional is better than a "this can be null" comment, but consider the possibility that the Map interface was designed to always return Optional. If I'm using a Map that I have complete control over, that I know what's in it (I think), then I'll call Map.get(x).orElseThrow(). This isn't an improvement over a Map.get(x) call that can return null. It's also uglier, and as shown by the Rust benchmark, much slower. I'd be happier with a Map interface that had a "tryGet" and "get" pair, where only the latter threw an exception. No need for Optional.
- valenterry 5y agoIt _is_ an improvement. If you just do "Map.get(x)" and you get null because your thinking was wrong, then the NPE will pop up potentially 10 layers later or an hour later, when the null-value was tried to be used in your program. On the other hand, with "Map.get(x).orElseThrow()" you will have an exception thrown immediately! Even better, you should customize that as "Map.get(x).orElseThrow(NoSuchElementException(x))" so that you know the value that was unexpectedly not in the list. That will make debugging much easier and will potentially fail a test case while a "Map.get(x)" might not cause the test to fail.