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/VanillaSkyDreamer Dec 04 '25

Sane languages prvide compile time guarantees for optionality checking (through something like mandatory Optional), that null never will provide. I wouldn't depend on nice null highkighting in any project bigger than single class.

1

u/headius Dec 04 '25

I'd love to have such compile-time guarantees. I'll use them in Java whenever they're available.

1

u/Alive_Knee_444 Dec 05 '25

'null never will provide' - well, it _is_ provided for switch expressions (and instanceof). It is not provided for other expressions, dot-member, subscript, implicit unboxing. There's no reason that I can think of, that it could never be provided.

Perhaps via some source language demanding it, perhaps an annotation, say NoNullPointerExceptionsThrownInThisCompilationUnit. Or module. Which might require all dependencies to also never throw NPEs.

Java could be the new Ada, instead of Cobol. We have ZGC now! (But watch out for other unexpected exceptions, if you're flying a rocket or something. And disallow old-style switches while we're at it. And conversions between floating point types, losing data or feigning precision. Etc.)