>
>
>
V6101. compareTo()-like methods can ret…


V6101. compareTo()-like methods can return not only the values -1, 0 and 1, but any values.

The analyzer has detected an expression comparing the return value of the 'Comparable.compareTo' method or other similar method with a specific non-zero value (1 and -1 in particular). However, the contract of this method in the Java specification implies that it can return any positive or negative value.

Whether the 'compareTo == 1' construct will return a correct value depends on its implementation. For this reason, such comparison with a specific value is considered a bad practice, which in some cases may lead to elusive bugs. Instead, use the 'compareTo > 0' expression.

Consider the following example:

void smt(SomeType st1, SomeType st2, ....)
{
  ....
  if (st1.compareTo(st2) == 1)
  {
    // some logic
  }
  ....
}

When working for a long time on a project, where the 'Comparable' interface is implemented in such a way that it allows comparing the return value of 'compareTo' with 1, the developer may get used to it. Switching over to another project, where the specifics of the method's implementation are different, the developer continues using this construct, which now returns different positive values depending on the circumstances.

The fixed version:

void smt(SomeType st1, SomeType st2, ....)
{
  ....
  if (st1.compareTo(st2) > 0)
  {
    // some logic
  }
  ....
}

The analyzer also issues the warning when it encounters a comparison of two 'compareTo' methods' return values. Such a situation is very uncommon, but it still must be considered.

This diagnostic is classified as: