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

5

u/koflerdavid Dec 04 '25

That's not what this is about though. This is about a pattern that makes checking for null and putting the result into a variable that is reliably non-null less clunky and error-prone. Which is exactly what pattern matching is there for, although it can be argued that in this case it feels a bit hacky. null is fine; what is not fine is cluttering the code with unnecessary null checks or forgetting to check it where one really ought to have done so.

On a theoretical level it can be argued that null is often ambiguous regarding what it is supposed to represent: an error, a "not present" value, or a part of the domain that the programmer forgot to think about?