Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Should not use equals when comparing object identity #274

Merged
merged 1 commit into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
"""
)

}