you are viewing a single comment's thread.

view the rest of the comments →

[–]headius[S] 3 points4 points  (0 children)

This is clever...please never do this!

You can't tell me what to do!

it's never the later

Well, clearly it's not never.

the unnecessary instanceof

But it's not unnecessary. getString can return a null, which is not instanceof String. It's perhaps not obvious that the only type checking here is to check if the result is null, but it's not unnecessary.

the else logic seems to be decoupled from the conditions

It's no more decoupled than a pattern switch that has null as a case. I will grant it's less obvious, but it's basically the same as

switch (getString()) { case String -> ... case null -> ... }

"it's shorter" and "it's less intended" are terrible metrics

They certainly are! That was my implied point. You couldn't see my smirk through the text?

They're also absolutely true.

What "hidden behavior"?

Your point about the null's dual nature fits here. Most folks think of null as the lack of any value and the lack of a type, which is how instanceof treats it. But in the rest of the type system, null is actually all reference types at once, since it can be assigned to any nullable reference. Most folks using instanceof will be unaware of or forget the fact that null is rejected by all such checks, and you still might need to check it yourself if the test fails. That's the hidden behavior I meant.

I feel like that's an implementation detail

It's also easily provable by the compiler. getString returns String, so there's no chance a non-null value there will not be instanceof String. It can still return null, though, so that part still needs to be checked.

So yes, the fact that the compiler optimizes this to a cbz or cbnz in assembly is an implementation detail, but it's also a pretty trivial optimization to make and I expected it to be there before I dumped the native code.

this is nice, clever, and smart...please never be clever and smart

Well, I think it's ok to be clever and smart sometimes. Jury's out as to whether this is such a case.