Re:Overhead of Returning Optional Values in Java and Rust
by valenterry on Saturday October 16, 2021 @09:44PM
(#28893252)
It _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.
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.