The instanceof[0] operator is typically banned from use in application code and often frowned upon in library implementations.
0 - https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.htm...
The instanceof[0] operator is typically banned from use in application code and often frowned upon in library implementations.
0 - https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.htm...
[1] I guess you would get some push back at review time if you used auto_ptr.
Once code such as the below is rejected in a code review, the next version often submitted is an "if-else-if" ladder using `instanceof` (which is effectively the same thing).
TheReturnType r = null;
try {
DomainType1 instance = (DomainType1)obj;
r = ...
}
catch (ClassCastException ex) {}
if (r == null)
try {
DomainType2 instance = (DomainType2)obj;
r = ...
}
catch (ClassCastException ex) {}
if (r == null)
try {
DomainType3 instance = (DomainType3)obj;
r = ...
}
catch (ClassCastException ex) {}
...
And yes, I have seen the above scenario played out in a professional setting.> Never seen this being banned. Whats the reason?
Its usage encodes a priori assumptions of what a super-type could be, often expressed in an "if-else-if tree", thus making the logic doing so needlessly brittle and difficult to maintain.
Library logic sometimes needs to use this construct (I'd argue those abstractions need to be rethought however), but an application which does exhibits a failure in domain modelling IMHO.
Over-eager code analyser tools are themselves a "smell", in that you either justifiably or unjustifiably don't trust your developers, trying to make up for their real or perceived deficits with a rather dumb tool. That never goes well in my experience.