109 lines
2.5 KiB
Plaintext
109 lines
2.5 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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.
|
|
|
|
== How to fix it
|
|
|
|
Replace any positive constant return value with 1.
|
|
Replace any negative constant return value with -1.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return Integer.MIN_VALUE; // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return -1; // Compliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return 42; // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return 1; // Compliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Noncompliant code example
|
|
|
|
It is compliant to return other values than -1, 0 or 1 if they are not constants.
|
|
|
|
[source,java,diff-id=3,diff-type=noncompliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return 42; // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=3,diff-type=compliant]
|
|
----
|
|
public int compareTo(Name name) {
|
|
if (condition) {
|
|
return hashCode() - name.hashCode(); // Compliant, not a constant
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-[Java SE 8 API Specification: Comparable.compareTo]
|
|
* https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#MIN_VALUE[Java SE 8 API Specification: Integer.MIN_VALUE]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Simply return -1.
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 21 Nov 2024, 16:48:00 Alban Auzeill wrote:
|
|
[test-code-support-investigation-for-java] Decision for scope: Keep 'Main'. FP if we want to test "compareTo" limits
|
|
|
|
endif::env-github,rspecator-view[]
|