Using “instanceOf” causes Production Risk

Software ResiliencyCode Reliability

How we detect

This code insight counts a violation each time an “instanceOf” is utilized

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

5362

Why you should care

Usually instanceOf is synonym of a bad design when it is used with against classes that you are developping.
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. 

Production Risk
5362

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.

See featuresHow it works