Skip to content

Commit 6ece6c7

Browse files
Add missing null check and fix cognitive complexity
1 parent 6d9a93d commit 6ece6c7

1 file changed

Lines changed: 21 additions & 10 deletions

File tree

java-checks/src/main/java/org/sonar/java/checks/VolatileVariablesOperationsCheck.java

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import java.util.HashSet;
2020
import java.util.List;
21+
import java.util.Optional;
2122
import java.util.Set;
2223
import javax.annotation.Nullable;
2324
import org.sonar.check.Rule;
@@ -86,6 +87,10 @@ private void checkUnaryExpression(UnaryExpressionTree unaryExpression) {
8687

8788
private void checkAssignment(AssignmentExpressionTree assignment) {
8889
IdentifierTree assignee = getVariableIdentifier(assignment.variable());
90+
if (assignee == null) {
91+
return;
92+
}
93+
8994
Symbol assigneeSymbol = assignee.symbol();
9095
if (!assigneeSymbol.isVolatile()) {
9196
return;
@@ -115,15 +120,8 @@ private static IdentifierTree getVariableIdentifier(ExpressionTree expressionTre
115120
}
116121

117122
private void reportIssueIfNotInExcludedContext(IdentifierTree identifier) {
118-
Type type = identifier.symbol().type();
119-
String recommendedType;
120-
if (type.is("boolean") || type.is("java.lang.Boolean")) {
121-
recommendedType = "AtomicBoolean";
122-
} else if (type.is("int") || type.is("java.lang.Integer")) {
123-
recommendedType = "AtomicInteger";
124-
} else if (type.is("long") || type.is("java.lang.Long")) {
125-
recommendedType = "AtomicLong";
126-
} else {
123+
Optional<String> recommendedType = recommendedType(identifier);
124+
if (recommendedType.isEmpty()) {
127125
return;
128126
}
129127

@@ -149,7 +147,20 @@ private void reportIssueIfNotInExcludedContext(IdentifierTree identifier) {
149147
current = current.parent();
150148
}
151149

152-
reportIssue(identifier, String.format("Use an \"%s\" for this field; its operations are atomic.", recommendedType));
150+
reportIssue(identifier, String.format("Use an \"%s\" for this field; its operations are atomic.", recommendedType.get()));
151+
}
152+
153+
private Optional<String> recommendedType(IdentifierTree identifier) {
154+
Type type = identifier.symbol().type();
155+
if (type.is("boolean") || type.is("java.lang.Boolean")) {
156+
return Optional.of("AtomicBoolean");
157+
} else if (type.is("int") || type.is("java.lang.Integer")) {
158+
return Optional.of("AtomicInteger");
159+
} else if (type.is("long") || type.is("java.lang.Long")) {
160+
return Optional.of("AtomicLong");
161+
} else {
162+
return Optional.empty();
163+
}
153164
}
154165

155166
private class SymbolCollector extends BaseTreeVisitor {

0 commit comments

Comments
 (0)