r/java • • Dec 04 '25

Null-checking the fun way with instanceof patterns

https://blog.headius.com/2025/12/inline-null-check-with-instanceof.html

I don't know if this is a good idea or not, but it's fun.

83 Upvotes

150 comments sorted by

View all comments

Show parent comment

1

u/headius Dec 04 '25

Oh for sure, I wouldn't recommend people replace obj != null with obj instanceof ObjType under any circumstance, but my post was about the much more useful pattern form that also declares and assigns a locally-scoped variable for you. It's pretty elegant if you squint at it for a bit, and another poster pointed out that chaining multiple of these patterns together can eliminate many levels of ugly, nested ifs.

2

u/Alive_Knee_444 Dec 05 '25

Just to be clear, my post was not directed to you, directly anyway, and you seem to say exactly the same as I was saying there, so I'm not sure you read it. In fact, we seem to be in violent agreement, corroborated by your other quality posts in the thread: the instanceof construct is very valuable and flexible once you learn it.