Checker UselessConstruction   as of Julia version 2.6.0 (built on 6 Sep 2018)

belongs to group Basic

Identify useless constructions of objects


Java allows a few expressions to be used as commands. Among them, object creation is allowed to be used as a command since it can in principle induce side-effects and hence have a computational sense. However, creation of objects that do not induce side-effects is useless and should be removed from the code; it might actually be the sign of a programming error.

Action: Check if the object creation was meant to have some side-effect and delete it.

Examples


Consider the following program:

public class Creations {
  public static boolean unnamed;

  public static void main(String[] args) {
    Test test = new Test(args.length > 0 ? args[0] : null);
    new Test("hello");
    new Test();
    System.out.println(test);
  }

  private static class Test {
    private final String name;

    private Test(String name) {
      this.name = name;
    }

    private Test() {
      this.name = "no name";
      unnamed = true;
    }

    @Override
    public String toString() {
      return name;
    }
  }
}

This checker issues the following warning:

Creations.java:6: [UselessConstruction: UselessConstructionWarning] Useless construction of Creations$Test

since the constructor of Test called at line 6 has no side-effects (beyond on the same object being constructed) and the constructed object is not used later. Note that no warning is issued at line 5, since the new Test object is assigned there to a local variable, nor at line 7, since the constructor used there has side-effects on field unnamed.

In this example, the programmer should remove the object creation at line 6 and check if that useless new statement was actually the sign of a programming error.