CodeQL 文档

未读局部变量

ID: java/local-variable-is-never-read
Kind: problem
Security severity: 
Severity: recommendation
Precision: high
Tags:
   - maintainability
   - useless-code
   - external/cwe/cwe-561
Query suites:
   - java-security-and-quality.qls

点击查看 CodeQL 仓库中的查询

从未读取的局部变量毫无用处。

作为一种良好的实践,应该没有未使用的或无用的代码。它使程序更难理解和维护,并可能浪费程序员的时间。

建议

此规则适用于从未使用的变量,以及仅写入但从未读取的变量。在这两种情况下,请确保没有缺少使用局部变量的操作。如果合适,只需删除声明。但是,如果写入变量,请确保保留赋值中的任何副作用。(有关更多详细信息,请参见示例。)

示例

在以下示例中,局部变量 oldQuantity 被分配了一个值,但从未读取。在示例的修复版本中,变量被删除,但保留了赋值中的对 items.put 的调用。

// Version containing unread local variable
public class Cart {
	private Map<Item, Integer> items = ...;
	public void add(Item i) {
		Integer quantity = items.get(i);
		if (quantity = null)
			quantity = 1;
		else
			quantity++;
		Integer oldQuantity = items.put(i, quantity);  // AVOID: Unread local variable
	}
}

// Version with unread local variable removed
public class Cart {
	private Map<Item, Integer> items = ...;
	public void add(Item i) {
		Integer quantity = items.get(i);
		if (quantity = null)
			quantity = 1;
		else
			quantity++;
		items.put(i, quantity);
	}
}

参考

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