This rule raises an issue when a ternary expression is used to perform a null-safe equality check between two objects.
In Java, this specifically refers to patterns like a != null ? a.equals(b) : b == null that can be replaced with
Objects.equals().
Manually checking for null before calling equals() is a common pattern, but it’s verbose and error-prone. Developers must remember to
handle all null combinations correctly, which increases the chance of mistakes.
Java provides Objects.equals() as a standard utility method that handles all null cases correctly. Using this method:
The Objects.equals() method is available since Java 7 and is the recommended way to perform null-safe equality comparisons.
Using manual null checks instead of Objects.equals() has several impacts:
Objects.equals() is harder to review and maintain.While this doesn’t directly cause bugs in correctly written code, it increases cognitive load and the risk of introducing errors during maintenance.
Replace the ternary null-check pattern with Objects.equals(). This handles all null cases correctly in a single method call.
The ternary pattern a != null ? a.equals(b) : b == null returns:
true when both a and b are nulltrue when both are non-null and equalfalse otherwiseThis is exactly the behavior of Objects.equals(a, b).
if (a != null ? a.equals(b) : b == null) { // Noncompliant
// ...
}
if (Objects.equals(a, b)) {
// ...
}