Java


JAVA.STRUCT.UUOBJ : Unused Object (Java)

Summary

Identify useless constructions of objects.

An object is created and not assigned, and its construction has no side-effects other than on the object itself.

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.

Properties

Class Name Unused Object (Java)
Significance reliability
Mnemonic JAVA.STRUCT.UUOBJ
Categories
CWE CWE:1164 Irrelevant Code
Availability Available for Java only.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Unused Object (Java)"

Example

public class Creations {
  public static boolean unnamed;

  public static void main(String[] args) {
      Test test = new Test(args.length > 0 ? args[0] : null);   // ok: object assigned to a local variable
      new Test("hello");   // "Unused Object (Java)" warning issued here
      new Test();                                               // ok: constructor has side effect on field 'unnamed'
      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;
    }
  }
}

Resolution

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

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.