openrewrite / openrewrite/rewrite-static-analysis
Recipe to prefer early return when handling some non-default code paths
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 62
- Forks
- 112
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 40
Description
What problem are you trying to solve?
Improve code readability in cases like a method declaration with one big if statement. One branch would contain a lot of logic, and the other branch would have a return and maybe one or two statements.
Such cases could be refactored to have the logic for non-default case at the top with an early return, and the rest of the logic in the top-level method body.
What precondition(s) should be checked before applying this recipe?
Some heuristics can be applied on when to apply the change. Finger in the air something like:
- at least 5 statements in the "default" branch
- at most 2 statements in the "non-default" branch.
Describe the situation before applying the recipe
public void processOrder(Order order) {
if (order != null && order.isValid() && !order.isCancelled()) {
// Main logic
System.out.println("Processing order: " + order.getId());
calculateTotals(order);
applyDiscounts(order);
updateInventory(order);
sendConfirmationEmail(order);
logOrderProcessed(order);
} else {
// Minimal branch
System.out.println("Order is invalid or cancelled. Skipping processing.");
return;
}
}
Describe the situation after applying the recipe
public void processOrder(Order order) {
if (order == null || !order.isValid() || order.isCancelled()) {
System.out.println("Order is invalid or cancelled. Skipping processing.");
return;
}
// Main logic
System.out.println("Processing order: " + order.getId());
calculateTotals(order);
applyDiscounts(order);
updateInventory(order);
sendConfirmationEmail(order);
logOrderProcessed(order);
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the before-and-after Java examples and the proposed heuristics for branch size and statement count. Inspect existing recipe implementations and unit-test conventions in the repository before deciding how the transformation should handle equivalent conditions. Done means the recipe applies the early-return form only when its preconditions hold and tests cover the shown transformation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100