Skip to content

Commit

Permalink
Should not use equals when comparing object identity (#274)
Browse files Browse the repository at this point in the history
fixes #273

Co-authored-by: tiesjr <ties@jdriven.com>
  • Loading branch information
vandeven and tiesjr committed Oct 20, 2022
1 parent 5fa4dce commit 5e832a5
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.openrewrite.java.search.UsesMethod;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;

import java.util.function.Supplier;

Expand Down Expand Up @@ -106,7 +107,18 @@ private boolean isEqualBinary(J.MethodInvocation method) {

J.Binary binary = (J.Binary) firstArgument;
J.Binary.Type operator = binary.getOperator();
return operator.equals(J.Binary.Type.Equal);

if (!operator.equals(J.Binary.Type.Equal)) {
return false;
}

// Prevent breaking identity comparison.
// Objects that are compared with == should not be compared with `.equals()` instead.
// Out of the primitives == is not allowed when both are of type String
return binary.getLeft().getType() instanceof JavaType.Primitive
&& binary.getRight().getType() instanceof JavaType.Primitive
&& !(binary.getLeft().getType() == JavaType.Primitive.String
&& binary.getRight().getType() == JavaType.Primitive.String);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,39 @@ class AssertTrueComparisonToAssertEqualsTest : JavaRecipeTest {
}
""",
)

@Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/273")
@Suppress("ConstantConditions", "SimplifiableAssertion")
@Test
fun doNotChangeToEqualsWhenCheckingOnObjectIdentityWithStrings() = assertUnchanged(
before = """
import org.junit.jupiter.api.Assertions;
public class Test {
void test() {
String a = "a";
String b = "a";
Assertions.assertTrue(a == b);
}
}
"""
)

@Issue("https://github.com/openrewrite/rewrite-testing-frameworks/issues/273")
@Suppress("ConstantConditions", "SimplifiableAssertion")
@Test
fun doNotChangeToEqualsWhenCheckingOnObjectIdentityWithObjects() = assertUnchanged(
before = """
import org.junit.jupiter.api.Assertions;
public class Test {
void test() {
Object a = new Object();
Object b = a;
Assertions.assertTrue(a == b);
}
}
"""
)

}

0 comments on commit 5e832a5

Please sign in to comment.