CodeQL 文档

局部变量和字段可能混淆

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

点击查看 CodeQL 仓库中的查询

如果方法声明的局部变量与字段同名,那么在阅读或修改程序时很容易将两者混淆。

建议

考虑使用不同的名称来区分字段和局部变量,以便明确区分它们。

示例

以下示例显示了一个名为 values 的局部变量,它与字段同名。

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;
	}
}

参考

  • ©GitHub, Inc.
  • 条款
  • 隐私