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

Classes should not access their own subclasses during initialization

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this reference to "xxx".
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      20min
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      DCL00-J.
    • FindBugs:
      IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION

      Description

      When a parent class references a member of a subclass during its own initialization, the results might not be what you expect because the child class might not have been initialized yet. This could create what is known as an "initialisation cycle", or even a deadlock in some extreme cases.

      To make things worse, these issues are very hard to diagnose so it is highly recommended you avoid creating this kind of dependencies.

      Noncompliant Code Example

      class Parent {
        static int field1 = Child.method(); // Noncompliant
        static int field2 = 42;
      
        public static void main(String[] args) {
          System.out.println(Parent.field1); // will display "0" instead of "42"
        }
      }
      
      class Child extends Parent {
        static int method() {
          return Parent.field2;
        }
      }
      

      See

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated: