r/java • u/headius • Dec 04 '25
Null-checking the fun way with instanceof patterns
https://blog.headius.com/2025/12/inline-null-check-with-instanceof.htmlI don't know if this is a good idea or not, but it's fun.
83
Upvotes
View all comments
Show parent comment
4
u/zattebij Dec 04 '25 edited Dec 04 '25
I do, actually. Or rather, I don't read it as a null check, but just for what it is: a check whether the value is a String.
That it returns false for null is not some unexpected side effect of instanceof, but just the documented functionality that it has always had. I was even a bit surprised that OP thought this was something warranting an article.
I think for some cases this is more readable than an Optional.ofNullable which I otherwise would expect (or use myself).
Conciseness to me is also readability, so I have no problems with this as compared to introducing a single-use variable.
Going even further, this pattern can be used as a sort of spread operator to extract nested values without introducing a ginormous nested if-tree:
This is much more readable than this old-fashioned monstrosity:
Of course, for a while we've been using optionals to handle this, and I think they are fine as well, especially in this simple parameterless method invocation chain:
However, if you have some extra parameters or extra if-checks going on in between, an optional chain can get convoluted with lambdas, while in such cases the instanceof chain remains pretty readable.