Rule Definition
The run-time type checking is a time expensive operation and as such should be avoided within loops.
In a more general matter, the use of InstanceOf operator, run-time type checking might indicate a misuse of Object Oriented programming. In deed, it is always recommended to design classes and interfaces so client code do not need to use InstanceOf operator and downcasting. The recommended way is to prefer polymorphism over InstanceOf operator and downcasting.
Remediation
Prefer polymorphism over 'is' operator and downcasting.
It is always recommended to design classes and interfaces so client code do not need to use InstanceOf operator and downcasting. The recommended way is to prefer polymorphism over InstanceOf operator and downcasting.
Violation Code Sample
class BaseExample { ... }
class Example1 extends BaseExample { ... }
class Example2 extends BaseExample { ... }
class Test {
BaseExample[] exList;
void method () {
for (int i = exList.length-1; i >= 0; i--) {
if (exList[i] instanceof Example1) { // VIOLATION
((Example1) exList[i]).aMethod1();
} elseif (exList[i] instanceof Example2) { // VIOLATION
((Example2) exList[i]).aMethod2();
}
}
}
Fixed Code Sample
class BaseExample { ... }
class Example1 extends BaseExample { ... }
class Examplet2 extends BaseExample { ... }
class Test {
BaseExample[] exList;
void method () {
for (int i = exList.length-1; i >= 0; i--) {
// common method to refactor aMethod1 and aMethod2
exList[i]).commonMethod(); // FIXED
}
}
}
}
Reference
Peter Sestoft (sestoft@dina.kvl.dk)
http://www.dina.dk/~sestoft/papers/performance.pdf
Related Technologies
Technical Criterion
Efficiency - Expensive Calls in Loops
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.