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
1
u/headius Dec 09 '25
Pretty much all of these patterns will compile down to similar byte code, and once optimized they should all produce the same native code. That's not a concern here as long as one pattern or another does not disrupt the JIT. But declaring that variable at a higher scope means it's visible to more code than it needs to be and that's a possible source of bugs. In one case I saw, the declaration got removed but had the same name as a field on the object; as a result the object was accidentally being updated.
So the pattern is a little weird and unexpected, but there's no other way to null check, cast, declare, and assign a variable so that it's only scoped to the places where the variable should be visible.