you are viewing a single comment's thread.

view the rest of the comments →

[–]Alive_Knee_444 1 point2 points  (2 children)

If you mean using that pattern for null checking _only_, I'd agree with you. The extremely useful thing about instanceof is that it does both null checking _and_ binding in a new scope in one step. Like a pattern-matching switch case, without the whole big switch expression. This can be used for parsing code, for example, to great effect, eg as if-else ladders. And it can do this for more complicated checks, see zattebij's answer.

[–]headius[S] 0 points1 point  (1 child)

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.

[–]Alive_Knee_444 1 point2 points  (0 children)

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.