openrewrite / rewrite-templating

Automated templating using code snippets.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simplify boolean expressions after a replacement

timtebeek opened this issue · comments

What problem are you trying to solve?

A lot of after templates in openrewrite/rewrite-migrate-java#271 produce boolean expressions to handle nullability. In some cases, the boolean expressions don't make sense if the argument is a literal, such as with

class EqualsIgnoreCase {
    @BeforeTemplate
    boolean before(String s, String other) {
        return StringUtils.equalsIgnoreCase(s, other);
    }
    @AfterTemplate
    boolean after(String s, String other) {
        return (s == null && other == null || s != null && s.equalsIgnoreCase(other));
    }
}

Which replaces the following

- boolean bool = StringUtils.equalsIgnoreCase(in, "other");
+ boolean bool = in == null && "other" == null || in != null && in.equalsIgnoreCase("other");

Describe the solution you'd like

The && "other" == null can likely be dropped through SimplifyBooleanExpression applied in doAfterVisit where applicable.

- boolean bool = StringUtils.equalsIgnoreCase(in, "other");
+ boolean bool = in == null || in != null && in.equalsIgnoreCase("other");

Have you considered any alternatives or workarounds?

No alternatives here I think, but a requirement for acceptance of the replaced suggestions.

Additional context

Are you interested in contributing this feature to OpenRewrite?