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

Inner class members should not shadow outer class "static" or type members

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Rename this [field|method|delegate|type|event|property] to not shadow the outer class' member with the same name.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way
    • Targeted languages:
      Java
    • Covered Languages:
      C#
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      10min
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      DCL51-J.
    • ReSharper:
      MemberHidesStaticFromOuterClass

      Description

      It's possible to name the members of an inner class the same as the static members of its enclosing class - possible, but a bad idea. That's because maintainers may be confused about which members are being used where. Instead the inner class' members should be renamed and all the references updated.

      Noncompliant Code Example

      class Outer
      {
        public static int A;
      
        public class Inner
        {
          public int A; //Noncompliant
          public int MyProp
          {
            get { return A; }  // Returns inner A. Was that intended?
          }
        }
      }
      

      After a rename

      class Outer
      {
        public static int A;
      
        public class Inner
        {
          public int B;
          public int MyProp
          {
            get { return A; }  // Still compiles and runs but functionality has changed
          }
        }
      }
      

      Compliant Solution

      class Outer
      {
        public static int A;
      
        public class Inner
        {
          public int InnerA;
          public int MyProp
          {
            get { return InnerA; }
          }
        }
      }
      

      See

        Attachments

          Activity

            People

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

              Dates

              Created:
              Updated: