Which do you prefer of these two? The goal is the same. If bar
is null then make foo
null and avoid the exception. In other languages there is the ?.
operator to help with this.
foo = bar == null ? null : bar.baz();
foo = bar != null ? bar.baz() : null;
I ask because I feel like the “English” of the first example is easier to read and has less negations so it is more straightforward, but the second one has the meat of the expression (bar.baz()
) more prominently.
I’d skip the ternary and go with
foo = Optional.ofNullable(bar) .map(Bar::baz) .orElse(null);
But if I didn’t, I’d use the first form.
In java 9 there is
Objects.requireNonNullElse(obj, defaultValue)
That wouldn’t help in the specific examples above but that’s still nice to know about!
In java 9 there is Objects.requireNonNullElse(obj, defaultValue)
I did not know this existed, this is amazing.
The first one. Readability is quicker, and you don’t have to stack context in your head if it’s ==.
Personally though, I prefer what I call short circuiting. Return right away if it’s null, basically input sanitization.
If I had to go with the ternary operator, I would choose not to negate the statement for the sake of readability.
If I had free will of choice I would prefer using the Optionals API, like @[email protected] did.
I think generally it’s preferably to work in the affirmative, i.e.
bar == null?
but I’ll admit I don’t stick to this 100% of the time and generally just use whatever feels better / more appropriate in the momentI think the meat being more prominent in the second one is subjective. If I were writing a method to do something like this with ifs, I would handle the edge cases first and return early from them. The meat would be what’s left after the edge cases. So this lines up with the first form.
I actually prefer
Optional.of(bar) .map(Bar::baz) .orElse(null)
You can crucify me but there is no way to miss the point in a quick glance here and I doubt that with JVM optimizations there is any meaningful performance impact, exceptionally in business code.
The second, or early return/continue/break.
But don’t forget the third option:
foo = null if (bar != null) foo = bar.baz();
This is much more readable if nontrivial; the only downside is that this inhibits the practice of ubiquitous
final
.Actually, doesn’t Java allow lazy
final
if you don’t initialize (that would require explicitelse
)? I speak too many languages …This is much less readable if non-trivial. It’s easy enough here, but now I need to search through the code to see where else foo was set.
Yes, Java allows lazy final like you say. I also prefer full blown if when it is non trivial or longer than a full line. (Wish we had if-expressions!)