Skip to content

Commit 6a182c1

Browse files
graememorganError Prone Team
authored and
Error Prone Team
committed
Yoda conditions: consider static fields which are in SHOUTY_CASE to be constant.
Motivated by `Boolean.TRUE`, but that seemed a bit special-casey. PiperOrigin-RevId: 610392208
1 parent 29d9335 commit 6a182c1

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

core/src/main/java/com/google/errorprone/bugpatterns/YodaCondition.java

+9-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import static com.google.errorprone.util.ASTHelpers.getNullnessValue;
2626
import static com.google.errorprone.util.ASTHelpers.getReceiver;
2727
import static com.google.errorprone.util.ASTHelpers.getSymbol;
28+
import static com.google.errorprone.util.ASTHelpers.isStatic;
2829
import static java.lang.String.format;
2930

3031
import com.google.errorprone.BugPattern;
@@ -41,6 +42,7 @@
4142
import com.sun.source.tree.Tree;
4243
import com.sun.tools.javac.code.Symbol.VarSymbol;
4344
import java.util.Objects;
45+
import java.util.regex.Pattern;
4446

4547
/** See the summary. */
4648
@BugPattern(
@@ -119,6 +121,12 @@ private static boolean seemsConstant(Tree tree) {
119121
return true;
120122
}
121123
var symbol = getSymbol(tree);
122-
return symbol instanceof VarSymbol && symbol.isEnum();
124+
if (!(symbol instanceof VarSymbol)) {
125+
return false;
126+
}
127+
return symbol.isEnum()
128+
|| (isStatic(symbol) && CONSTANT_CASE.matcher(symbol.getSimpleName().toString()).matches());
123129
}
130+
131+
private static final Pattern CONSTANT_CASE = Pattern.compile("[A-Z0-9_]+");
124132
}

core/src/test/java/com/google/errorprone/bugpatterns/YodaConditionTest.java

+44
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,50 @@ public void primitive() {
5353
.doTest();
5454
}
5555

56+
@Test
57+
public void boxedBoolean() {
58+
refactoring
59+
.addInputLines(
60+
"Test.java",
61+
"class Test {",
62+
" boolean yoda(Boolean a) {",
63+
" return Boolean.TRUE.equals(a);",
64+
" }",
65+
"}")
66+
.addOutputLines(
67+
"Test.java",
68+
"import java.util.Objects;",
69+
"class Test {",
70+
" boolean yoda(Boolean a) {",
71+
" return Objects.equals(a, Boolean.TRUE);",
72+
" }",
73+
"}")
74+
.doTest();
75+
}
76+
77+
@Test
78+
public void boxedVsUnboxedBoolean() {
79+
refactoring
80+
.addInputLines(
81+
"Test.java",
82+
"class Test {",
83+
" boolean yoda(boolean a) {",
84+
" return Boolean.TRUE.equals(a);",
85+
" }",
86+
"}")
87+
.addOutputLines(
88+
"Test.java",
89+
"class Test {",
90+
" boolean yoda(boolean a) {",
91+
// NOTE: this is a broken fix! We could detect this if it turns out to be an issue in
92+
// practice.
93+
" return a.equals(Boolean.TRUE);",
94+
" }",
95+
"}")
96+
.allowBreakingChanges()
97+
.doTest();
98+
}
99+
56100
@Test
57101
public void enums() {
58102
refactoring

0 commit comments

Comments
 (0)