r/java • u/edurbs • Feb 17 '26
Objects.requireNonNullElse
I must have been living in a cave. I just discovered that this exists.
I can code
City city = Objects.requireNonNullElse(form.getCity(), defaultCity);
... instead of:
City city = form.getCity();
if(city == null){
city = defaultCity;
}
113
Upvotes
View all comments
Show parent comment
2
u/ForeverAlot Feb 18 '26 edited Feb 18 '26
Yes; the context I understood was: starting from zero, what ought one write?
An (effort invested in) optimization is "premature" if undertaken without empirical proof—or at the very least a strong and qualified intuition from first principles—that the result materially improves upon the baseline benchmark.
There is little (performance) reason to spend time replacing the
Optionalpattern in question with an equivalent null check. To do so would have such negligible impact that it barely qualifies as an optimization at all, at least outside of pathological cases (for example, millions of executions in an environment prevented from performing inlining).But there is considerable reason to not spend time writing that pattern in the first place; it is not materially clearer or safer, it's not idiomatic Java, and it can never be faster than its classic alternative (even if the JVM can eventually make it as fast as).
The original claim that the proposed pattern is "more readable" is subjective, of course; but for precisely that reason "readability" is not an effective metric for evaluating code. In comparison, metrics such as idiomacy, debuggability, and safety are easier (if not exactly easy) to debate. For example, a construct like
is completely idiomatic Java code with trivial debuggability, but it has two safety issues avoidable in the
Optionalcounterpart (and one safety issue they share).I think
is superior to both other examples because it has no safety issues (provided that null values are to be considered unwanted).
There are several other options I omitted under pretense of brevity, including some I quite like; find them in other comments.