-
Notifications
You must be signed in to change notification settings - Fork 90
PreferEarlyReturn recipe #656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
greg-at-moderne
wants to merge
13
commits into
main
Choose a base branch
from
greg-PreferEarlyReturn
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
eece5ed
PreferEarlyReturn stub
greg-at-moderne c378cde
Simple impl
greg-at-moderne cbf9f3a
Better count of statements
greg-at-moderne 47f42b4
Testing for non-void methods too
greg-at-moderne e56b770
Merge remote-tracking branch 'origin/main' into greg-PreferEarlyReturn
greg-at-moderne a8ed23c
Merge remote-tracking branch 'origin/main' into greg-PreferEarlyReturn
greg-at-moderne 76406df
Tests to use interfaces, not classes
greg-at-moderne 3fd529b
Remove comments
greg-at-moderne 00a00ee
Simplify by removing special handling of negations
greg-at-moderne 28fdc55
Simplify code by inlining some methods
greg-at-moderne 2c39614
Merge branch 'main' into greg-PreferEarlyReturn
greg-at-moderne 31818ec
Autoformat + UnwrapElseAfterReturn in postVisit
greg-at-moderne a54b92c
Merge branch 'main' into greg-PreferEarlyReturn
greg-at-moderne File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
163 changes: 163 additions & 0 deletions
163
src/main/java/org/openrewrite/staticanalysis/PreferEarlyReturn.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,163 @@ | ||||||||||||||
| /* | ||||||||||||||
| * Copyright 2025 the original author or authors. | ||||||||||||||
| * <p> | ||||||||||||||
| * Licensed under the Moderne Source Available License (the "License"); | ||||||||||||||
| * you may not use this file except in compliance with the License. | ||||||||||||||
| * You may obtain a copy of the License at | ||||||||||||||
| * <p> | ||||||||||||||
| * https://docs.moderne.io/licensing/moderne-source-available-license | ||||||||||||||
| * <p> | ||||||||||||||
| * Unless required by applicable law or agreed to in writing, software | ||||||||||||||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||||||||||||||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||||||||||
| * See the License for the specific language governing permissions and | ||||||||||||||
| * limitations under the License. | ||||||||||||||
| */ | ||||||||||||||
| package org.openrewrite.staticanalysis; | ||||||||||||||
|
|
||||||||||||||
| import org.jspecify.annotations.NonNull; | ||||||||||||||
| import org.jspecify.annotations.Nullable; | ||||||||||||||
| import org.openrewrite.ExecutionContext; | ||||||||||||||
| import org.openrewrite.Recipe; | ||||||||||||||
| import org.openrewrite.TreeVisitor; | ||||||||||||||
| import org.openrewrite.java.JavaVisitor; | ||||||||||||||
| import org.openrewrite.java.tree.*; | ||||||||||||||
| import org.openrewrite.marker.Markers; | ||||||||||||||
|
|
||||||||||||||
| import java.time.Duration; | ||||||||||||||
| import java.util.Collections; | ||||||||||||||
| import java.util.Set; | ||||||||||||||
| import java.util.concurrent.atomic.AtomicBoolean; | ||||||||||||||
|
|
||||||||||||||
| import static org.openrewrite.Tree.randomId; | ||||||||||||||
|
|
||||||||||||||
| public class PreferEarlyReturn extends Recipe { | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public String getDisplayName() { | ||||||||||||||
| return "Prefer early returns"; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public String getDescription() { | ||||||||||||||
| return "Refactors methods to use early returns for error/edge cases, reducing nesting and improving readability. " + | ||||||||||||||
| "The recipe heuristically identifies if-else statements where the if block contains the main logic and the " + | ||||||||||||||
| "else block contains a simple return. It then inverts the condition and moves the else block " + | ||||||||||||||
| "to the beginning of the method with an early return, allowing the main logic to be un-indented."; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public Set<String> getTags() { | ||||||||||||||
| return Collections.emptySet(); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public Duration getEstimatedEffortPerOccurrence() { | ||||||||||||||
| return Duration.ofMinutes(2); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public TreeVisitor<?, ExecutionContext> getVisitor() { | ||||||||||||||
| return new PreferEarlyReturnVisitor(); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| private static class PreferEarlyReturnVisitor extends JavaVisitor<ExecutionContext> { | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public @Nullable J postVisit(@NonNull J tree, ExecutionContext executionContext) { | ||||||||||||||
| J ret = super.postVisit(tree, executionContext); | ||||||||||||||
| if (getCursor().pollMessage("PREFER_EARLY_RETURN") != null) { | ||||||||||||||
|
Comment on lines
+67
to
+69
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||
| ret = (J) new UnwrapElseAfterReturn().getVisitor().visit(ret, executionContext, getCursor().getParent()); | ||||||||||||||
| } | ||||||||||||||
| return ret; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public J visitIf(J.If ifStatement, ExecutionContext ctx) { | ||||||||||||||
| J.If if_ = (J.If) super.visitIf(ifStatement, ctx); | ||||||||||||||
|
|
||||||||||||||
| if (!isEligibleForEarlyReturn(if_)) { | ||||||||||||||
| return if_; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| J.ControlParentheses<Expression> invertedCondition = if_.getIfCondition().withTree(invertExpression(if_.getIfCondition().getTree())); | ||||||||||||||
| J.If newIf = if_.withIfCondition(invertedCondition) | ||||||||||||||
| .withThenPart(if_.getElsePart().getBody()) | ||||||||||||||
| .withElsePart(new J.If.Else( | ||||||||||||||
| randomId(), | ||||||||||||||
| if_.getElsePart().getPrefix(), | ||||||||||||||
| Markers.EMPTY, | ||||||||||||||
| JRightPadded.build(if_.getThenPart()) | ||||||||||||||
| )); | ||||||||||||||
|
|
||||||||||||||
| newIf = maybeAutoFormat(if_, newIf, ctx); | ||||||||||||||
| getCursor().dropParentUntil(J.Block.class::isInstance).putMessage("PREFER_EARLY_RETURN", "unwrap"); | ||||||||||||||
| return newIf; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| private boolean isEligibleForEarlyReturn(J.If ifStatement) { | ||||||||||||||
| if (ifStatement.getElsePart() == null || | ||||||||||||||
| !(ifStatement.getThenPart() instanceof J.Block) || | ||||||||||||||
| !(ifStatement.getElsePart().getBody() instanceof J.Block)) { | ||||||||||||||
| return false; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| J.Block thenBlock = (J.Block) ifStatement.getThenPart(); | ||||||||||||||
| J.Block elseBlock = (J.Block) ifStatement.getElsePart().getBody(); | ||||||||||||||
|
|
||||||||||||||
| int thenStatements = (thenBlock == null || thenBlock.getStatements() == null) ? 0 : thenBlock.getStatements().size(); | ||||||||||||||
| int elseStatements = (elseBlock == null || elseBlock.getStatements() == null) ? 0 : elseBlock.getStatements().size(); | ||||||||||||||
|
|
||||||||||||||
| if (thenStatements < 5 || (thenStatements - elseStatements) < 2) { | ||||||||||||||
| // heuristics for determining if the then block is the "main flow" over the else block | ||||||||||||||
| return false; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| return hasReturnOrThrowStatement(elseBlock); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| private boolean hasReturnOrThrowStatement(J.Block block) { | ||||||||||||||
| if (block == null || block.getStatements() == null) { | ||||||||||||||
| return false; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| AtomicBoolean hasReturnOrThrow = new AtomicBoolean(false); | ||||||||||||||
| new JavaVisitor<AtomicBoolean>() { | ||||||||||||||
| @Override | ||||||||||||||
| public J visitReturn(J.Return return_, AtomicBoolean flag) { | ||||||||||||||
| flag.set(true); | ||||||||||||||
| return return_; | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| @Override | ||||||||||||||
| public J visitThrow(J.Throw thrown, AtomicBoolean flag) { | ||||||||||||||
| flag.set(true); | ||||||||||||||
| return thrown; | ||||||||||||||
| } | ||||||||||||||
| }.visit(block, hasReturnOrThrow); | ||||||||||||||
|
|
||||||||||||||
| return hasReturnOrThrow.get(); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| private Expression invertExpression(Expression expr) { | ||||||||||||||
| Expression toNegate = expr; | ||||||||||||||
| if (expr instanceof J.Binary) { | ||||||||||||||
| toNegate = new J.Parentheses<>( | ||||||||||||||
| randomId(), | ||||||||||||||
| expr.getPrefix(), | ||||||||||||||
| Markers.EMPTY, | ||||||||||||||
| JRightPadded.build(expr.withPrefix(Space.EMPTY)) | ||||||||||||||
| ); | ||||||||||||||
| } | ||||||||||||||
|
|
||||||||||||||
| return new J.Unary( | ||||||||||||||
| randomId(), | ||||||||||||||
| toNegate.getPrefix(), | ||||||||||||||
| Markers.EMPTY, | ||||||||||||||
| new JLeftPadded<>(Space.EMPTY, J.Unary.Type.Not, Markers.EMPTY), | ||||||||||||||
| toNegate.withPrefix(Space.EMPTY), | ||||||||||||||
| JavaType.Primitive.Boolean | ||||||||||||||
| ); | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
| } | ||||||||||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.