It's not very obvious. Object casting inside the {} (even in case of instance of) can confuse. Such magic in code makes it easy to read but not understand IMHO
This code might confuse a developer. He/She might end up wondering how a method that accepts rectangles can now accommodate a Shape object, which happens to be a super type.
sure it COULD be confusing because it is just another thing to consider when reading code (auto type casting from if)., but i think in the end it will be very benefitial once everyone is used to it
It's broken. If 'object' is changed by multiple threads, another thread may change its value after the 'if' statement passed true, causing a ClassCastException.
This happens because you are trying to do a runtime checking (the value of the variable at that exact moment) using a compiler trick, which is a build-time check. This is different from, say, generics, 'cause generics, when used correctly (no warnings, no 'ignore me' annotations) guarantee that the variable will NEVER be assigned with an invalid value. This instanceof compiler trick doesn't do anything but do a cast for you, with all risks of a manual cast.
Comments
dkharlamov replied ago:
It's not very obvious. Object casting inside the {} (even in case of instance of) can confuse. Such magic in code makes it easy to read but not understand IMHO
joojoo joojoo replied ago:
This code might confuse a developer. He/She might end up wondering how a method that accepts rectangles can now accommodate a Shape object, which happens to be a super type.
zynasis replied ago:
sure it COULD be confusing because it is just another thing to consider when reading code (auto type casting from if)., but i think in the end it will be very benefitial once everyone is used to it
Mikael Grev replied ago:
If anything, with(object as Rectangle) {} or similar might be used. Or for (..). Questionable if the gains would outweigh the costs though.
htowninsomniac replied ago:
The nullness checker from JSR 308 already does a similar kind of type refinement in if-statements. I'd like to see a prototype of this.
ronaldtm replied ago:
It's broken. If 'object' is changed by multiple threads, another thread may change its value after the 'if' statement passed true, causing a ClassCastException.
This happens because you are trying to do a runtime checking (the value of the variable at that exact moment) using a compiler trick, which is a build-time check. This is different from, say, generics, 'cause generics, when used correctly (no warnings, no 'ignore me' annotations) guarantee that the variable will NEVER be assigned with an invalid value. This instanceof compiler trick doesn't do anything but do a cast for you, with all risks of a manual cast.
ksuha replied ago:
That is very good point, Ronald. I take my idea back.
zynasis replied ago:
good call mate
ksuha replied ago:
Right, you have to be genius to understand instanceof.
Voters For This Link (7)
Voters Against This Link (24)