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

"interface" instances should not be cast to concrete types

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this cast and edit the interface to add the missing functionality.
    • Default Severity:
      Critical
    • Impact:
      High
    • Likelihood:
      Low
    • Covered Languages:
      C#
    • Irrelevant for Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      1h
    • Analysis Scope:
      Main Sources

      Description

      Needing to cast from an interface to a concrete type indicates that something is wrong with the abstractions in use, likely that something is missing from the interface. Instead of casting to a discrete type, the missing functionality should be added to the interface. Otherwise there is a risk of runtime exceptions.

      Noncompliant Code Example

      public interface IMyInterface
      {
        void DoStuff();
      }
      
      public class MyClass1 : IMyInterface
      {
        public int Data { get { return new Random().Next(); } }
      
        public void DoStuff()
        {
          // TODO...
        }
      }
      
      public static class DowncastExampleProgram
      {
        static void EntryPoint(IMyInterface interfaceRef)
        {
          MyClass1 class1 = (MyClass1)interfaceRef;  // Noncompliant
          int privateData = class1.Data;
      
          class1 = interfaceRef as MyClass1;  // Noncompliant
          if (class1 != null)
          {
            // ...
          }
        }
      }
      

      Exceptions

      Casting to object doesn't raise an issue, because it can never fail.

      static void EntryPoint(IMyInterface interfaceRef)
      {
        var o = (object)interfaceRef;
        ...
      }
      

        Attachments

          Issue Links

          1.
          Java RSPEC-3503 Language-Specification Active Unassigned

            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: