Skip to content

Commit

Permalink
Recommend using var for var unused = ...; and `var thrown = asser…
Browse files Browse the repository at this point in the history
…tThrows(MyException.class, () -> ...);`

PiperOrigin-RevId: 610457244
  • Loading branch information
kluever authored and Error Prone Team committed Feb 26, 2024
1 parent af37d35 commit ad513d5
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
11 changes: 11 additions & 0 deletions core/src/main/java/com/google/errorprone/bugpatterns/Varifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ public final class Varifier extends BugChecker implements VariableTreeMatcher {
&& isSameType(((MethodSymbol) symbol).getReturnType(), symbol.owner.type, s);
});

private static final Matcher<ExpressionTree> ASSERT_THROWS =
staticMethod().onClass("org.junit.Assert").named("assertThrows");

@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
var symbol = getSymbol(tree);
Expand All @@ -77,6 +80,14 @@ public Description matchVariable(VariableTree tree, VisitorState state) {
|| hasImplicitType(tree, state)) {
return NO_MATCH;
}
// Foo unused = ...;
if (symbol.getSimpleName().contentEquals("unused")) {
return fix(tree);
}
// MyException exception = assertThrows(MyException.class, () -> ...);
if (ASSERT_THROWS.matches(initializer, state)) {
return fix(tree);
}
// Foo foo = (Foo) bar;
if (initializer instanceof TypeCastTree
&& isSameType(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,50 @@ public void fromFactoryMethod() {
"}")
.doTest();
}

@Test
public void varUnused() {
refactoringHelper
.addInputLines(
"Test.java",
"class Test {",
" public void trim(String string) {",
" String unused = string.trim();",
" }",
"}")
.addOutputLines(
"Test.java",
"class Test {",
" public void trim(String string) {",
" var unused = string.trim();",
" }",
"}")
.doTest();
}

@Test
public void assertThrows() {
refactoringHelper
.addInputLines(
"Test.java",
"import static org.junit.Assert.assertThrows;",
"class Test {",
" public void testFoo() {",
" Object nil = null;",
" NullPointerException thrown = ",
" assertThrows(NullPointerException.class, () -> nil.toString());",
" }",
"}")
.addOutputLines(
"Test.java",
"import static org.junit.Assert.assertThrows;",
"class Test {",
" public void testFoo() {",
" Object nil = null;",
" var thrown = ",
" assertThrows(NullPointerException.class, () -> nil.toString());",
" }",
"}")
.doTest();
}
}

0 comments on commit ad513d5

Please sign in to comment.