Checker UselessInstanceof   as of Julia version 2.5.0 (built on 4 Jul 2018)

belongs to group Basic

Identify useless instanceof operations


This checker looks for instanceof operators that are useless, in the sense that they are always true or always false and can hence be removed from the code. This can improve the efficiency of the program. Moreover, a useless instanceof test is often the sign of a programming bug.

Action: check if the instanceof operator can be actually removed and that it is not the sign of an actual programming bug.

Examples


Consider the following program:

public class Main {
  public static void main(String[] args) {
    A a = new B();
    switch ((int) (System.currentTimeMillis() % 3)) {
      case 0: case 1:
        a = new A(); break;
      case 2:
        a = new C(); break;
    }
    if (a instanceof C)
      foo(a);
  }

  private static void foo(A par) {
    if (par instanceof B)   // this check is useless
      System.out.println("par is a B");
  }
}

public class A {}
public class B extends A {}
public class C extends B {}

This checker issues the following warning:

Main.java:15: [UselessInstanceof: UselessInstanceofWarning] This instanceof seems useless

since it is always true and can be removed. In this case, the programmer should probably consider to define method foo as foo(B par).