rspec/rules/S3043/java/rule.adoc

61 lines
1.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Perhaps counter-intuitively, a ``++compareTo++`` method is _expected_ to throw a ``++NullPointerException++`` if passed a null argument, and a ``++ClassCastException++`` if the argument is of the wrong type. So there's no need to null-test or type-test the argument.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public int compareTo(Object obj) {
if (obj == null) { // Noncompliant
return -1;
}
if (! obj instanceof MyClass.class) { // Noncompliant
return -1;
}
MyObject myObj = (MyObject) obj;
// ...
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public int compareTo(Object obj) {
MyObject myObj = (MyObject) obj;
// ...
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Remove this null-test of "xxx".
* Remove this type-test of "xxx".
'''
== Comments And Links
(visible only on this page)
=== on 11 Jun 2015, 18:11:17 Ann Campbell wrote:
CodePro: Allow compareTo to Throw Exceptions
=== on 16 Jun 2015, 13:14:22 Nicolas Peru wrote:
Not an easy one, but looks good.
endif::env-github,rspecator-view[]