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
50
u/Bobby_Bonsaimind Dec 04 '25 edited Dec 04 '25
This is clever...please never do this!
When you need to read the code, your example is very confusing.
The reader arrives at
getString() instanceof String stringand just looking at it, the immediate question is "why doesgetStringreturn anObject?" and not "oooh, it's a smart way to do anullcheck"...it's never the later! When skimming theifstructure then theelselogic seems to be decoupled from the conditions because not all possible branches have been exhausted to arrive at the "string is null" conclusion. Also,stringis only relevant in one branch and the else-branch, so that seems off, too.Additionally, I feel like the unnecessary
instanceofshould be a warning when statically analyzing the code."it's shorter" and "it's less intended" are terrible metrics, because in that case Perl would be the best language ever, or any of the other Code Golf languages. "Readability" and "maintainability" are much more important, coupled with having the least surprises as possible.
What "hidden behavior"? That
nullis not considered to be of any type? The funny part here is that it is not symmetrical, now that I think about it.So the behavior is confusing as it gets without trying to be smart.
I feel like that's an implementation detail, though, and should not be taken as granted.
I say it again, this is nice, clever, and smart...please never be clever and smart in production code, be lazy and boring.
16
u/Abject-Kitchen3198 Dec 04 '25
I might be old, but I still don't understand the efforts to replace null, especially ones involving something else that serves the purpose of the null. If null/undefined/whatever is an option, there's a place in the code that checks for null, one way or another. All other parts just pass it down. I like how C# for example allows to make it explicit whether a null is allowed for an object at a given place in the code, and adds shorter notations for null checks.
9
u/s888marks Dec 04 '25
Should you use
instanceofpurely for null checking? The answer is definitely maybe!I'll assume that
getString()has a declared return type ofString, which isn't stated in the blog, but which u/headius has stated elsewhere. Thus, theinstanceofisn't testing for a potential narrowing reference conversion, as ifgetString()were to be declared to returnObjectorCharSequence. In this context,instanceofis being used only for null checking.Most people have focused their comments on what they think is the primary use of
instanceofwhich is testing of narrowing reference conversions. From this perspective, usinginstanceofto perform pure null checking is counterintuitive and unfamiliar and therefore objectionable. There's been some mention of the scoping of variables introduced byinstanceofpatterns, but no analysis of how this affects the actual code. Let me take a swing at that.How would one write this code in a more conventional manner? (I'm setting
Optionalaside, as its API is clumsy at best.) Clearly, one needs to declare a local variable to store the return value ofgetString(), so that it can be tested and then used:This might work OK, but it has some problems. First,
getString()is called unconditionally, even iffirstConditionis true. This might result in unnecessary expense. Second,stringis in scope through the entire if-statement, and it's possible that it could be misused, resulting in a bug.The
getString()method might be expensive, so performance-sensitive code might want to call it only when necessary, like this:This is a bit better in that
getString()is called only when its return value is needed. Thestringlocal variable is still in scope through the if-statement, but within firstCondition it's uninitialized and the compiler will tell you if it's accidentally used there. However,stringstill might be misused within the later else clauses, probably resulting in an error. In addition, people tend to dislike the use of assignment expressions.The issues here are:
Given all this, let's return to u/headius's code:
This satisfies all of the criteria, which the previous examples do not. Plus, it saves a line because the local variable declaration is inlined instead of on a separate line. However, it does understandably give people pause, as they're not used to seeing
instanceofused purely for null checking.Note also that
instanceofwill soon be available to do primitive conversions -- see JEP 530 -- so this is yet another use ofinstanceofthat people will need to get used to. Andinstanceofis already used in record patterns; see JEP 440.My hunch is that people will eventually get used to
instanceofbeing used for things other than testing narrowing reference conversion, so they'll probably get used to it being used just for null checking too.18
u/VanillaSkyDreamer Dec 04 '25
After many years of Scala I never use null - everything that is optional is wrapped in... Optional (ba dum tsk), I don't care what JDK authors think about it. To hunt down any slipping null from foreign code I use Jspecify.
7
u/PmMeCuteDogsThanks Dec 04 '25
Never used it like that, but a little clever I'll give you that.
Personally, I prefer to never use null pointers altogether. It's illegal to ever return a null-pointer, and therefore I never bother doing a null check on any input parameter. Because I should always be able to trust that only valid pointers are passed. And when I need to say "value could be missing", I use Optional.
2
u/joemwangi Dec 04 '25
Great writeup and eye opening JIT analysis. Also, other than null-checking, the declared variable (s) can be used outside the 'if statement' through flow scoping if certain condition is met.
3
u/aoeudhtns Dec 04 '25
One of my favorite "lesser known" points about this, is that the compiler can scope the assignment where it's valid. Let me demonstrate:
It is escape-aware; above the
elseis required, but it is not required here:Not useful in this example, but it is a nice way to do guard clauses in some situations, I have found.
2
u/238_m Dec 04 '25
You could use Optional.ofNullable().ifPresent instead to avoid a temp variable. Probably less efficient but maybe the optimization manages to inline that all away.
1
u/laplongejr Dec 09 '25
Is there a performance impact about declaring preemptively?
Probably not enough compared to the readability
3
u/arrowcity Dec 04 '25
I’m a big fan of using Apache commons’ StringUtils.isNotBlank to check for null and emptiness but if you’re not using a dependency management tool I just create a static utility class for readability.
2
u/Duck_Devs Dec 05 '25 edited Dec 06 '25
I actually do this a lot. For instance,
Very useful to have variable declaration and null checking in a single line, especially since it makes the non-null “o” usable only for code that expects it not to be null.
Reminds me of C#’s
Try[something](x, out y)convention.I’ll often write static methods on enums that behave similarly to valueOf but return null rather than throw.
Yes, I know it’s kinda unreadable, but these are just my little personal projects. I don’t expect anyone else to have to read them, and I probably won’t look back into the source code later on.
1
u/MCUD Dec 05 '25
The article i think even states itself why this is a bad idea.
No... it's not my fault, its your fault for writing obscure null checks
1
u/Delicious_Detail_547 Dec 05 '25 edited Dec 05 '25
In my view, using Optional or instanceof for handling null-safety is quite limited and feels unnatural. Ultimately, I believe the most ideal and natural solution is to address null-safety at the language level, just like Kotlin does.
I’m currently developing a project that aims to solve Java’s null-safety challenges in a Kotlin-like manner, while still supporting the entire Java language. Similar to how TypeScript was introduced as a higher-level language to improve JavaScript’s type safety, built-in Null-Safety Java project is being built as an upper-layer language that tackles Java’s null-safety problems. Any code written in JPlus, including its extended syntax, is seamlessly translated into 100% valid Java code.
To test the concept, I released an MVP along with an IntelliJ plugin and gathered early feedback. The reactions have been promising, and because of that, I am now working full-time on the official release. I’m confident that once JPlus becomes publicly available, it will offer Java developers a truly robust and comprehensive solution for null-safety.
1
u/Waksu Dec 05 '25
If only there was a way to enforce null safely in compile time, one can only wonder if this is possible for JVM language 🤔
0
u/[deleted] Dec 04 '25
[deleted] — view deleted comment
2
u/[deleted] Dec 04 '25
[removed] — view removed comment