openrewrite / rewrite-templating

Automated templating using code snippets.
Apache License 2.0
16 stars 7 forks source link

Simplify boolean expressions after a replacement #28

Closed timtebeek closed 1 year ago

timtebeek commented 1 year ago

What problem are you trying to solve?

A lot of after templates in https://github.com/openrewrite/rewrite-migrate-java/pull/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?