Skip to content

Commit da89c8b

Browse files
SONARJAVA-2511 S4030: Do not raise if there is no usage at all (#5208)
Co-authored-by: Dorian Burihabwa <75226315+dorian-burihabwa-sonarsource@users.noreply.github.com>
1 parent 1df8945 commit da89c8b

2 files changed

Lines changed: 12 additions & 1 deletion

File tree

java-checks-test-sources/default/src/main/java/checks/unused/UnusedCollectionCheckSample.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,13 @@ int getLengthComp(String a, String b, String c) {
1717
return a.length() + b.length() + c.length();
1818
}
1919

20+
int getLengthNoUsageAtAll(String a, String b, String c) {
21+
// Do not report in this case: lack of usage may indicate unreliable data about the symbol
22+
// and this case should also be covered by S1481 and S1854.
23+
List<String> strings = new ArrayList<>();
24+
return a.length() + b.length() + c.length();
25+
}
26+
2027
int getLengthCompTested(String a, String b, String c) {
2128
List<String> strings = new ArrayList<>();
2229
strings.add(a);

java-checks/src/main/java/org/sonar/java/checks/unused/UnusedCollectionCheck.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,8 @@
3333
import org.sonar.plugins.java.api.tree.VariableTree;
3434

3535
/**
36-
* Check for collections that are new read, that is the only operations are adding and removing elements.
36+
* Check for collections whose content is not used,
37+
* that is, the only operations on them are adding and removing elements.
3738
*/
3839
@Rule(key = "S4030")
3940
public class UnusedCollectionCheck extends IssuableSubscriptionVisitor {
@@ -52,6 +53,9 @@ public void visitNode(Tree tree) {
5253
if (symbol.type().isSubtypeOf("java.util.Collection") &&
5354
symbol.isLocalVariable() &&
5455
isInitializedByConstructor(variableTree.initializer()) &&
56+
// Do not raise without any usage: usages() may be unreliable,
57+
// moreover, this case is in scope of S1481 and S1854 (unused variable and assignment)
58+
!symbol.usages().isEmpty() &&
5559
symbol.usages().stream().allMatch(UnusedCollectionCheck::isWriteOnly)) {
5660
reportIssue(variableTree.simpleName(), "Consume or remove this unused collection");
5761
}

0 commit comments

Comments
 (0)