Container contents are never accessed¶
ID: java/unused-containerKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - maintainability - useless-code - external/cwe/cwe-561Query suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
If the contents of a collection or map are never accessed in any way, then it is useless and the code that updates it is effectively dead code. Often, such objects are left over from an incomplete refactoring, or they indicate an underlying logic error.
Recommendation¶
Either remove the collection/map if it is genuinely unnecessary, or ensure that its elements are accessed.
Example¶
In the following example code, thereachable method determines whether a node in a tree is reachable fromROOT. It maintains a setreachableNodes, which contains all nodes that have previously been found to be reachable. Most likely, this set is meant to act as a cache to avoid spurious recomputation, but as it stands the code never checks whether any node is contained in the set.
privateSet<Node>reachableNodes=newHashSet<Node>();booleanreachable(Noden){booleanreachable;if(n==ROOT)reachable=true;elsereachable=reachable(n.getParent());if(reachable)reachableNodes.add(n);returnreachable;}
In the following modification of the above example,reachable checks the cache to see whether the node has already been considered.
privateSet<Node>reachableNodes=newHashSet<Node>();booleanreachable(Noden){if(reachableNodes.contains(n))returntrue;booleanreachable;if(n==ROOT)reachable=true;elsereachable=reachable(n.getParent());if(reachable)reachableNodes.add(n);returnreachable;}
References¶
Java API Specification:Collection,Map.
Common Weakness Enumeration:CWE-561.