openrewrite / rewrite-templating

Automated templating using code snippets.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

When before template parameter is used twice in after template, do not call method invocations such as `iterator.next()` twice

timtebeek opened this issue · comments

What problem are you trying to solve?

Given a recipe such as the following

private static class IsEmpty {
    @BeforeTemplate
    boolean before(String s) {
        return StringUtils.isEmpty(s);
    }

    @AfterTemplate
    boolean after(String s) {
        return (s == null || s.isEmpty());
    }
}

When the input parameter is a method invocation such as iterator.next()
Then the template likely should not make any changes.

Have you considered any alternatives or workarounds?

  • Optional.ofNullable() could work, but isn't as clean of a replacement.
  • Marking inputs as not nullable could limit matching if supported in type system or analysis.
  • Introducing a variable isn't easily possible in all contexts, nor does that help the readability.

Additional context

@knutwannheden had this to add in chat

We could probably without too much effort develop out own @matches annotation where the corresponding Matcher receives a J as input. That would allow you to check if it is a MethodInvocation.