rspec/rules/S2638/java/rule.adoc

61 lines
1.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Because a subclass instance may be cast to and treated as an instance of the superclass, overriding methods should uphold the aspects of the superclass contract that relate to the Liskov Substitution Principle. Specifically, if the parameters or return type of the superclass method are marked with any of the following: ``++@Nullable++``, ``++@CheckForNull++``, ``++@NotNull++``, ``++@NonNull++``, and ``++@Nonnull++``, then subclass parameters are not allowed to tighten the contract, and return values are not allowed to loosen it.
=== Noncompliant code example
[source,java]
----
public class Fruit {
private Season ripe;
private String color;
public void setRipe(@Nullable Season ripe) {
this.ripe = ripe;
}
public @NotNull Integer getProtein() {
return 12;
}
}
public class Raspberry extends Fruit {
public void setRipe(@NotNull Season ripe) { // Noncompliant
this.ripe = ripe;
}
public @Nullable Integer getProtein() { // Noncompliant
return null;
}
}
----
== Resources
* https://en.wikipedia.org/wiki/Liskov_substitution_principle[Wikipedia - Liskov substitution principle]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Remove this "xxx" annotation to honor the overridden method's contract.
* Equals method should accept null parameters and return false.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]