Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2638

Method overrides should not change contracts

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Hide
      * Remove this "xxx" annotation to honor the overridden method's contract.
      * Equals method should accept null parameters and return false.
      Show
      * Remove this "xxx" annotation to honor the overridden method's contract. * Equals method should accept null parameters and return false.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java, Python
    • Irrelevant for Languages:
      C#, VB.Net
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources
    • FindBugs:
      NP_METHOD_PARAMETER_TIGHTENS_ANNOTATION,NP_METHOD_RETURN_RELAXING_ANNOTATION

      Description

      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

      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;
        }
      }
      

      See

        Attachments

          Issue Links

          1.
          Python RSPEC-5716 Language-Specification Active Unassigned

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                ann.campbell.2 Ann Campbell
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated: