openrewrite / openrewrite/rewrite-migrate-java

Enhance IfElseIfConstructToSwitch to support "return" statements

Open
#776 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement java 21+ recipe
Dominant language
Java
Stars
156
Forks
130
Avg merge
20h 57m
Merged PRs (30d)
21

Description

Currently the IfElseIfConstructToSwitch recipe does not convert to a switch if any of the parts would return.
However, if all branches would return, we could convert it to and it could be a potential candidate. Only the intermediate phase of having returns in the case is not valid, hence would not be picked up by:

    static String formatter(Object obj) {
        if (obj instanceof String s) {
            return s;
        } else if (obj instanceof Long l) {
            return String.valueOf(l);
        } else {
            throw new IllegalStateException("Unexpected value: " + obj);
        }
    }

could become

    static String formatter(Object obj) {
        return switch (obj) {
            case String s -> s;
            case Long l -> String.valueOf(l);
            default -> throw new IllegalStateException("Unexpected value: " + obj);
        };
    }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the IfElseIfConstructToSwitch recipe entry point and review how it handles branches containing return statements. Read the related issue 718 for the existing limitation, then verify the behavior against the Java example in this issue. Done means eligible all-return branches are converted to an equivalent switch expression while intermediate return cases remain excluded.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
tooling
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.