CodeQL documentation

Possible confusion of local and field

ID: java/local-shadows-field
Kind: problem
Severity: recommendation
Precision: high
Tags:
   - maintainability
   - readability
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

If a method declares a local variable with the same name as a field, then it is very easy to mix up the two when reading or modifying the program.

Recommendation

Consider using different names for the field and local variable to make the difference between them clear.

Example

The following example shows a local variable values that has the same name as a field.

public class Container
{
	private int[] values; // Field called 'values'
	
	public Container (int... values) {
		this.values = values;
	}

	public Container dup() {
		int length = values.length;
		int[] values = new int[length];  // Local variable called 'values'
		Container result = new Container(values);
		return result;
	}
}

References