Skip to content

Commit 15e89ff

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

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

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

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@
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;
24+
import javax.swing.text.html.Option;
2325
import org.sonar.check.Rule;
2426
import org.sonar.java.model.ExpressionUtils;
2527
import org.sonar.java.model.ModifiersUtils;
@@ -86,6 +88,10 @@ private void checkUnaryExpression(UnaryExpressionTree unaryExpression) {
8688

8789
private void checkAssignment(AssignmentExpressionTree assignment) {
8890
IdentifierTree assignee = getVariableIdentifier(assignment.variable());
91+
if (assignee == null) {
92+
return;
93+
}
94+
8995
Symbol assigneeSymbol = assignee.symbol();
9096
if (!assigneeSymbol.isVolatile()) {
9197
return;
@@ -115,15 +121,8 @@ private static IdentifierTree getVariableIdentifier(ExpressionTree expressionTre
115121
}
116122

117123
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 {
124+
Optional<String> recommendedType = recommendedType(identifier);
125+
if (recommendedType.isEmpty()) {
127126
return;
128127
}
129128

@@ -149,7 +148,20 @@ private void reportIssueIfNotInExcludedContext(IdentifierTree identifier) {
149148
current = current.parent();
150149
}
151150

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

155167
private class SymbolCollector extends BaseTreeVisitor {

0 commit comments

Comments
 (0)