Skip to content

Commit ad513d5

Browse files
klueverError Prone Team
authored andcommitted
Recommend using var for var unused = ...; and var thrown = assertThrows(MyException.class, () -> ...);
PiperOrigin-RevId: 610457244
1 parent af37d35 commit ad513d5

2 files changed

Lines changed: 57 additions & 0 deletions

File tree

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ public final class Varifier extends BugChecker implements VariableTreeMatcher {
6767
&& isSameType(((MethodSymbol) symbol).getReturnType(), symbol.owner.type, s);
6868
});
6969

70+
private static final Matcher<ExpressionTree> ASSERT_THROWS =
71+
staticMethod().onClass("org.junit.Assert").named("assertThrows");
72+
7073
@Override
7174
public Description matchVariable(VariableTree tree, VisitorState state) {
7275
var symbol = getSymbol(tree);
@@ -77,6 +80,14 @@ public Description matchVariable(VariableTree tree, VisitorState state) {
7780
|| hasImplicitType(tree, state)) {
7881
return NO_MATCH;
7982
}
83+
// Foo unused = ...;
84+
if (symbol.getSimpleName().contentEquals("unused")) {
85+
return fix(tree);
86+
}
87+
// MyException exception = assertThrows(MyException.class, () -> ...);
88+
if (ASSERT_THROWS.matches(initializer, state)) {
89+
return fix(tree);
90+
}
8091
// Foo foo = (Foo) bar;
8192
if (initializer instanceof TypeCastTree
8293
&& isSameType(

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

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,4 +176,50 @@ public void fromFactoryMethod() {
176176
"}")
177177
.doTest();
178178
}
179+
180+
@Test
181+
public void varUnused() {
182+
refactoringHelper
183+
.addInputLines(
184+
"Test.java",
185+
"class Test {",
186+
" public void trim(String string) {",
187+
" String unused = string.trim();",
188+
" }",
189+
"}")
190+
.addOutputLines(
191+
"Test.java",
192+
"class Test {",
193+
" public void trim(String string) {",
194+
" var unused = string.trim();",
195+
" }",
196+
"}")
197+
.doTest();
198+
}
199+
200+
@Test
201+
public void assertThrows() {
202+
refactoringHelper
203+
.addInputLines(
204+
"Test.java",
205+
"import static org.junit.Assert.assertThrows;",
206+
"class Test {",
207+
" public void testFoo() {",
208+
" Object nil = null;",
209+
" NullPointerException thrown = ",
210+
" assertThrows(NullPointerException.class, () -> nil.toString());",
211+
" }",
212+
"}")
213+
.addOutputLines(
214+
"Test.java",
215+
"import static org.junit.Assert.assertThrows;",
216+
"class Test {",
217+
" public void testFoo() {",
218+
" Object nil = null;",
219+
" var thrown = ",
220+
" assertThrows(NullPointerException.class, () -> nil.toString());",
221+
" }",
222+
"}")
223+
.doTest();
224+
}
179225
}

0 commit comments

Comments
 (0)