How we detect
public final class BadInstanceOf {
public static void doSomething(Animal aAnimal){
if (aAnimal instanceof Fish){
Fish fish = (Fish)aAnimal;
fish.swim();
}
else if (aAnimal instanceof Spider){
Spider spider = (Spider)aAnimal;
spider.crawl();
}
}
// PRIVATE //
private static class Animal {}
private static final class Fish extends Animal {
void swim(){}
}
private static final class Spider extends Animal {
void crawl(){}
}
}
Remedy –
public final class BadInstanceOfFixed {
public static void doSomething(Animal aAnimal){
//calls different versions of move, specific to
//each Animal
aAnimal.move();
}
// PRIVATE //
private static class Animal {
void move(){
//do nothing
}
}
private static final class Fish extends Animal {
void move(){
//move like a fish
}
}
private static final class Spider extends Animal {
void move(){
//move like a spider
}
}
}
This report lists all artifacts that reference instanceOf used with an internal class or interface as argument.
It provides the following information:
Artifact full name, the number of occurrences of this detected in the artifact
Why you should care
instanceof operator should be used only as a last resort, and that an overridden method is usually (but not always) a better alternative.
Business Impacts
Having a series of “InstanceOf” in an application is considered to be bad design from a technical perspective and that can lead to a lack of productivity in one’s portfolio.Â
CAST recommendations
About CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.