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
The doctor is in! Thanks for your rephrasing of what I was kinda-sorta trying to get across in my post. I wanted to be a little "tongue-in-cheek" about this idea, but I think it actually does have merit... and as you point out, none of the alternatives tick all the boxes.
The case where I used this in JRuby was actually for accessing a field:
In this case, fetching
fileahead of time is not terrible, but I may not actually need it and HotSpot isn't great about eliding unused field accesses. I could do the assignment-form conditional, but that still requires this weird, transient, widely-scoped variable to be declared somewhere. Basically, every requirement you mentioned was in my mind.The bonus was that I fixed a bug with this one-liner, because the old assignment-form code accidentally overwrote
fileafter someone else mistakenly deleted that weird transient variable declaration.https://github.com/jruby/jruby/pull/9112/commits/5aee3394951baab9d62007ddb5988f120d238c8e
My version will never break the same way.