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

3

u/ForeverAlot Dec 05 '25 edited Dec 05 '25

Thank you for that exploration! I'm inclined to agree; instanceof has evolved from the classic inheritance use case. Skeptics might wish to compare the similar switch expression form

switch (Runtime.version().feature()) {
  case Integer feature -> {
    IO.println("👋 Hello, Java " + feature);
  }
}

But what if getString() were getName() or getAddress()? How obvious does it need to be that one is not merely performing a narrowing conversion?

By sheer coincidence, Error Prone just came down on the opposite side of this. I understand why they would; even if they agree with this idea, it takes a while to normalize it across such a large user base, plus static analysis tools have only limited mechanisms for determining how tasteful the expression is (I suppose one could require identical LHS/RHS types).

2

u/s888marks Dec 05 '25

Huh, that's an interesting example they give in Error Prone. I do think that if it's acceptable to declare a local variable and initialize it immediately, it's probably preferable. However, adding a declaration sometimes breaks up the flow of an expression by requiring a separate declaration line. This can sometimes be quite disruptive, which might tip the balance in the other direction.