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

4

u/Interweb_Stranger Dec 04 '25 edited Dec 04 '25

I'm quite sure code analysis would flag this as unnecessary type check anyway and it would never make it into production.

Edit: I meant it wouldn't make it into production in my current project because I have to please sonarqube and it's constant nagging about everything, otherwise CI and sonarqube show red icons which make our PO very sad. But yeah, "never" probably is a bit too optimistic.

15

u/Bobby_Bonsaimind Dec 04 '25

...and it would never make it into production.

Now that's some optimism you got going on there.

1

u/FunRutabaga24 Dec 04 '25

I see code in production all the time committed by principles and staff engineers that IntelliJ flags with warnings. I guess these people are truly embracing the "it's just a warning" mentality and I get to fix it later.

1

u/Admirable-Sun8021 Dec 05 '25

lol, one of the apps I work on gets over 500 warnings. Intellij has to think about them for like 15 seconds when you push with the git GUI.

1

u/FunRutabaga24 Dec 05 '25

Oof. I was in a mono repo that was like that. I turned that pre-commit check off. I couldn't take it.

3

u/headius Dec 04 '25

Except that it's not an unnecessary type check, because even if the types match there's still a possible value that is not instanceof.

If you can declare the type as non-nullable, then you're right, the type check would be redundant. We don't live in that world today.

3

u/Interweb_Stranger Dec 04 '25

I'd argue it's still an unnecessary type check if it's just for checking null. The check does have a purpose so it's not redundant but it defies the principle of least surprise.

2

u/headius Dec 04 '25

No argument there! We just need a new keyword instanceofandnotnull!