The literals should be first in String comparisons

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: java-best-practices/literals-first-in-comparison

Language: Java

Severity: Warning

Category: Best Practices

Description

One should always prioritize using a string literal as the first arguments in any string comparison. This approach serves as a preventive measure against NullPointerExceptions because when the second argument is null, instead of encountering an exception, the comparisons will simply yield false results.

Non-Compliant Code Examples

class Foo {
    boolean bar(String x) {
        return x.equals("42"); // should be "42".equals(x)
    }
    boolean bar(String x) {
        return x.equalsIgnoreCase("42"); // should be "42".equalsIgnoreCase(x)
    }
    boolean bar(String x) {
        return (x.compareTo("bar") > 0); // should be: "bar".compareTo(x) < 0
    }
    boolean bar(String x) {
        return (x.compareToIgnoreCase("bar") > 0); // should be: "bar".compareToIgnoreCase(x) < 0
    }
    boolean baz(String x) {
        return x.contentEquals("baz"); // should be "baz".contentEquals(x)
    }
}

Compliant Code Examples

class Foo {
    boolean bar(String x) {
        return "42".equals(x);
    }
    boolean bar(String x) {
        return "42".equalsIgnoreCase(x);
    }
    boolean bar(String x) {
        return "bar".compareTo(x) < 0;
    }
    boolean bar(String x) {
        return "bar".compareToIgnoreCase(x) < 0;
    }
    boolean baz(String x) {
        return "baz".contentEquals(x);
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis