Checker UselessAssignment   as of Julia version 2.4 (built on 23 Oct 2017)

belongs to group Basic

Identify useless assignments


This checker finds assignments to local variables that are useless and could be consequently removed from code, hence obtaining a more efficient program. In some cases, these assignments hide actual bugs in the logic of the code.

Action: Remove the assignment and check if it actually hided a more serious algorithmical issue.

Examples


Consider the following program:

import java.util.HashMap;
import java.util.Map;

public class Test {
  private int f;
	
  public Test(int f) {
    f = process(f);
		
    Map factory = new HashMap<>();
    factory = buildFactory();
    go(factory);
  }

  private int process(int x) {
    return x * 17 + 13;
  }

  private Map buildFactory() {
    Map result = new HashMap<>();
    result.put("value", f);
	
    return result;
  }

  private void go(Map factory) {
    for (String s: factory.keySet())
      System.out.println(s);
  }
}

This checker issues the following warnings:

Test.java:8: [UselessAssignment: AssignmentToUnusedVariableWarning] The value written here into f is never read again later. Did you want to write into the synonym field instead?
Test.java:10: [UselessAssignment: AssignmentToUnusedVariableWarning] The value written here into factory is never read again later

since the values written at lines 8 and 10 are not read again later. Note that both useless assignments hide more serious issues. The assignment at line 8 was probably meant to write into field f rather than into local variable f. Hence, that field remains uninitialized after the execution of the constructor. The assignment at line 10 initializes factory to a value that gets immediately discarded after, at line 11. This is a waste of time and memory.

In this example, the programmer should probably write into field f and initialize factory to the return value of buildFactory(), immediately, as follows:

import java.util.HashMap;
import java.util.Map;

public class Test {
  private int f;
	
  public Test(int f) {
    this.f = process(f);
		
    Map factory = buildFactory();
    go(factory);
  }

  ...
}