The Comparable.compareTo
method returns a negative integer, zero, or a positive integer to indicate whether the object is less than,
equal to, or greater than the parameter. The sign of the return value or whether it is zero is what matters, not its magnitude.
Returning a positive or negative constant value other than the basic ones (-1, 0, or 1) provides no additional information to the caller. Moreover, it could potentially confuse code readers who are trying to understand its purpose.
Replace any positive constant return value with 1. Replace any negative constant return value with -1.
public int compareTo(Name name) { if (condition) { return Integer.MIN_VALUE; // Noncompliant } }
public int compareTo(Name name) { if (condition) { return -1; // Compliant } }
public int compareTo(Name name) { if (condition) { return 42; // Noncompliant } }
public int compareTo(Name name) { if (condition) { return 1; // Compliant } }
It is compliant to return other values than -1, 0 or 1 if they are not constants.
public int compareTo(Name name) { if (condition) { return 42; // Noncompliant } }
public int compareTo(Name name) { if (condition) { return hashCode() - name.hashCode(); // Compliant, not a constant } }