Skip to content

Commit bcc951a

Browse files
committed
Adding a check for Void return type and no return expression
1 parent 7112d6e commit bcc951a

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/main/java/org/openrewrite/staticanalysis/UnnecessaryReturnAsLastStatement.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@
2020
import org.openrewrite.TreeVisitor;
2121
import org.openrewrite.java.JavaIsoVisitor;
2222
import org.openrewrite.java.tree.J;
23+
import org.openrewrite.java.tree.JavaType;
2324
import org.openrewrite.java.tree.Statement;
25+
import org.openrewrite.java.tree.TypeUtils;
2426

2527
import java.util.ArrayList;
2628
import java.util.List;
@@ -58,7 +60,7 @@ private J.Block maybeRemoveReturnAsLastStatement(J.Block b) {
5860
}
5961
Statement lastStatement = statements.get(statements.size() - 1);
6062
List<Statement> allButLast = statements.subList(0, statements.size() - 1);
61-
if (lastStatement instanceof J.Return) {
63+
if (lastStatement instanceof J.Return && ((J.Return) lastStatement).getExpression() == null) {
6264
return b.withStatements(allButLast);
6365
} else if (lastStatement instanceof J.If) {
6466
J.If ifStatement = (J.If) lastStatement;
@@ -77,7 +79,11 @@ private J.Block maybeRemoveReturnAsLastStatement(J.Block b) {
7779
@Override
7880
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext ctx) {
7981
J.MethodDeclaration m = super.visitMethodDeclaration(method, ctx);
80-
return m.withBody(maybeRemoveReturnAsLastStatement(m.getBody()));
82+
if (TypeUtils.asPrimitive(m.getType()) == JavaType.Primitive.Void) {
83+
return m.withBody(maybeRemoveReturnAsLastStatement(m.getBody()));
84+
} else {
85+
return m;
86+
}
8187
}
8288
};
8389
}

src/test/java/org/openrewrite/staticanalysis/UnnecessaryReturnAsLastStatementTest.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,4 +105,19 @@ void world(int i) {
105105
}
106106
"""));
107107
}
108+
109+
@Test
110+
void notChangingNonVoidMethods() {
111+
//language=java
112+
rewriteRun(
113+
java(
114+
"""
115+
class Hello {
116+
int world(int i) {
117+
return i + 436;
118+
}
119+
}
120+
"""));
121+
}
122+
108123
}

0 commit comments

Comments
 (0)