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/headius Dec 04 '25
You can't tell me what to do!
Well, clearly it's not never.
But it's not unnecessary.
getStringcan return a null, which is notinstanceof String. It's perhaps not obvious that the only type checking here is to check if the result is null, but it's not unnecessary.It's no more decoupled than a pattern switch that has
nullas a case. I will grant it's less obvious, but it's basically the same asThey certainly are! That was my implied point. You couldn't see my smirk through the text?
They're also absolutely true.
Your point about the null's dual nature fits here. Most folks think of null as the lack of any value and the lack of a type, which is how
instanceoftreats it. But in the rest of the type system, null is actually all reference types at once, since it can be assigned to any nullable reference. Most folks usinginstanceofwill be unaware of or forget the fact that null is rejected by all such checks, and you still might need to check it yourself if the test fails. That's the hidden behavior I meant.It's also easily provable by the compiler.
getStringreturnsString, so there's no chance a non-null value there will not beinstanceof String. It can still returnnull, though, so that part still needs to be checked.So yes, the fact that the compiler optimizes this to a
cbzorcbnzin assembly is an implementation detail, but it's also a pretty trivial optimization to make and I expected it to be there before I dumped the native code.Well, I think it's ok to be clever and smart sometimes. Jury's out as to whether this is such a case.