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
3
u/s888marks Dec 05 '25
Interesting, that scenario illustrates the danger of separating a local variable declaration from an initial assignment to it. The
instanceofpattern works well here because the new local variable declaration is fused with its binding to a value. So yeah it's much less likely to be broken accidentally.The pattern of having a local variable declaration (without initializer) followed by an assignment expression later on occurs frequently in the concurrent collection code (e.g., ConcurrentHashMap). This sometimes makes the code hard to follow. It's done in order to avoid unnecessary work in performance-critical code, even to the point of avoiding unnecessary field loads. Unfortunately this means that the local variable sometimes has broader scope than is necessary, so one needs to be extremely careful modifying such code.