2023-08-04 16:14:12 +02:00
This rule raises an issue when an overriding method changes a contract defined in a superclass.
2023-05-25 14:18:12 +02:00
== 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.
2023-08-04 16:14:12 +02:00
=== Code examples
2023-05-25 14:18:12 +02:00
2023-08-04 16:14:12 +02:00
==== Noncompliant code example
2023-05-25 14:18:12 +02:00
2023-08-04 16:14:12 +02:00
[source,java,diff-id=1,diff-type=noncompliant]
2023-05-25 14:18:12 +02:00
----
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 {
2023-08-04 16:14:12 +02:00
public void setRipe(@NotNull Season ripe) { // Noncompliant: the ripe argument annotated as @Nullable in parent class
2023-05-25 14:18:12 +02:00
this.ripe = ripe;
}
2023-08-04 16:14:12 +02:00
public @Nullable Integer getProtein() { // Noncompliant: the return type annotated as @NotNull in parent class
2023-05-25 14:18:12 +02:00
return null;
}
}
----
2023-08-04 16:14:12 +02:00
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
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(@Nullable Season ripe) {
this.ripe = ripe;
}
public @NotNull Integer getProtein() {
return 12;
}
}
----
2023-05-25 14:18:12 +02:00
== Resources
2023-08-04 16:14:12 +02:00
=== Documentation
2023-05-25 14:18:12 +02:00
2023-08-04 16:14:12 +02:00
* SOLID - https://en.wikipedia.org/wiki/Liskov_substitution_principle[Wikipedia - Liskov substitution principle]
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
* Remove this "xxx" annotation to honor the overridden method's contract.
* Equals method should accept null parameters and return false.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]