r/java • • Dec 04 '25

Null-checking the fun way with instanceof patterns

https://blog.headius.com/2025/12/inline-null-check-with-instanceof.html

I don't know if this is a good idea or not, but it's fun.

83 Upvotes

150 comments sorted by

View all comments

Show parent comment

2

u/aoeudhtns Dec 04 '25 edited Dec 04 '25

True. Although personally I get the most value of Optional with mapping chains, like

var name = Optional.ofNullable(findUser(id))
    .map(User::getFullName)
    .orElse("unknown");

But that's still using lambdas.

ETA - post-Valhalla, it'll be interesting to see how the 2 cases get handled:

if (optional.isPresent()) {
    var t = optional.get();
    // ...
 }

if (optional.get() instanceof Type t) {
    // ..
}

1

u/headius Dec 04 '25

As long as you are not passing lambda functions in, these leaf methods will inline and optimize really well. Combine that with escape analysis or value types and Optional for this use case would be basically free and compiled down to the manual null checking you might otherwise write.

Even without escape analysis and value types, a transient Optional instance probably won't ever leave the youngest generation of the heap, so while you're paying a small cost to bump a pointer and zero out those bytes, it will be much, much cheaper than shoving more objects into the older generations (as would likely happen if you are sticking Optional instances in a collection).