rewrite icon indicating copy to clipboard operation
rewrite copied to clipboard

Add constructor calls to RemoveMethodInvocations

Open davidh44 opened this issue 9 months ago • 2 comments

Recipe RemoveMethodInvocations currently does not cover constructor calls. This PR adds functionality for that

What's your motivation?

Would like to remove certain POJO instantiations.

Have you considered any alternatives or workarounds?

As a workaround for my use case, I used a JavaVisitor, checked the JavaType, and returned null.

davidh44 avatar Apr 08 '25 20:04 davidh44

Thanks for the runnable example! Had a brief look. We'll likely need to add something like

    @Override
    public J visitNewClass(J.NewClass newClass, ExecutionContext ctx) {
        J nc = super.visitNewClass(newClass, ctx);
        
        // TODO
        
        return nc;
    }

And then do something very similar to https://github.com/openrewrite/rewrite/blob/d21bb4175596e935e94b287b68b6611b5d351a81/rewrite-java/src/main/java/org/openrewrite/java/RemoveMethodInvocationsVisitor.java#L52-L72

Where we need a bit more care is to adapt https://github.com/openrewrite/rewrite/blob/d21bb4175596e935e94b287b68b6611b5d351a81/rewrite-java/src/main/java/org/openrewrite/java/RemoveMethodInvocationsVisitor.java#L74-L77

As right now we'd fail on that first conditional; we need to also allow where expression instanceof J.NewClass.

timtebeek avatar Apr 08 '25 20:04 timtebeek

Added logic for constructor removal and additional tests.

Two issues came up, wondering if you could provide some pointers:

a) Given that almost all constructor calls will be assigned to a variable, how can we remove the entire line? Should we use visitVariableDeclaration()? Can we view the assignment method there?

b) As above, we want to remove the entire line, including chained method calls, e.g., new Date().toInstant(). What's the proper way to get rid of the chained method calls?

davidh44 avatar Apr 09 '25 22:04 davidh44

This PR is stale because it has been open for 90 days with no activity. Remove stale label or comment or this will be closed in two weeks. PRs may be reopened when there is renewed interest.

github-actions[bot] avatar Sep 15 '25 04:09 github-actions[bot]