> I've never heard of that being banned. It hasn't been banned anywhere i've written Java.
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.
If you have to ask an object what its type is, you're probably about to cast it, and these are operations that the language doesn't enforce that you do together (and so the habit of casting can lead to the habit of casting without the check...). There are times when it's appropriate but generally if you have to ask what type an object is, your code is already starting to smell (because typically dispatching on type is handled by polymorphism, not be the programmer manually implementing it).
>> The instanceof[0] operator is typically banned from use in application code and often frowned upon in library implementations.
> 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.
It can be a code smell, but there are legitimate uses. This is not something that I would ever "ban".
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.
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...