Skip to content

Commit

Permalink
Use new J.SwitchExpression constructor
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden authored and punkratz312 committed Jan 23, 2025
1 parent a482f1e commit b38ff0a
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public class EqualsAvoidsNullVisitor<P> extends JavaVisitor<P> {
private static final String JAVA_LANG_STRING = "java.lang.String ";
private static final MethodMatcher EQUALS = new MethodMatcher(JAVA_LANG_STRING + "equals(java.lang.Object)");
private static final MethodMatcher EQUALS_IGNORE_CASE = new MethodMatcher(JAVA_LANG_STRING + "equalsIgnoreCase(java.lang.String)");
private static final MethodMatcher COMPARE_TO = new MethodMatcher(JAVA_LANG_STRING + "compareTo(java.lang.String)");
private static final MethodMatcher COMPARE_TO_IGNORE_CASE = new MethodMatcher(JAVA_LANG_STRING + "compareToIgnoreCase(java.lang.String)");
private static final MethodMatcher CONTENT_EQUALS = new MethodMatcher(JAVA_LANG_STRING + "contentEquals(java.lang.CharSequence)");

EqualsAvoidsNullStyle style;
Expand Down Expand Up @@ -90,7 +92,9 @@ private boolean hasCompatibleArgument(J.MethodInvocation m) {
private boolean isStringComparisonMethod(J.MethodInvocation methodInvocation) {
return EQUALS.matches(methodInvocation) ||
(!style.getIgnoreEqualsIgnoreCase() && EQUALS_IGNORE_CASE.matches(methodInvocation)) ||
CONTENT_EQUALS.matches(methodInvocation);
CONTENT_EQUALS.matches(methodInvocation) ||
COMPARE_TO.matches(methodInvocation) ||
COMPARE_TO_IGNORE_CASE.matches(methodInvocation);
}

private void maybeHandleParentBinary(J.MethodInvocation m) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,58 @@ public class A {
);
}

@DocumentExample
@Test
void invertConditional_compareTo() {
rewriteRun(
//language=java
java(
"""
public class A {
{
String s = null;
if(s.compareTo("test")) {}
}
}
""",
"""
public class A {
{
String s = null;
if("test".compareTo(s)) {}
}
}
"""
)
);
}

@DocumentExample
@Test
void invertConditional_compareToIgnoreCase() {
rewriteRun(
//language=java
java(
"""
public class A {
{
String s = null;
if(s.compareToIgnoreCase("test")) {}
}
}
""",
"""
public class A {
{
String s = null;
if("test".compareToIgnoreCase(s)) {}
}
}
"""
)
);
}

@Test
void removeUnnecessaryNullCheck() {
rewriteRun(
Expand Down

0 comments on commit b38ff0a

Please sign in to comment.