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

Switches should be used for sequences of simple tests

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Convert this "if/else if" structure into a "switch".
    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Legacy Key:
      ComplexIfShouldBeReplacedByCase
    • Targeted languages:
      C#, C, C++, Cobol, Flex, Java, JavaScript, Objective-C, PHP, Python, VB.Net, VB6
    • Covered Languages:
      PL/SQL
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Implementation details:

      Description

      When a single primitive is tested against three or more values in an if/else if structure, it should be converted to a switch instead for greater readability.

      Noncompliant Code Example

      public void doSomething(int i) {
        if (i == 0) {
          // ...
        }
        else if (i == 1) {
          // ...
        }
        else if (i == 2) {
          // ...
        }
        else if (i == 3) {
          // ...
        }
        else {
          // ...
        }
      
      

      Compliant Solution

      public void doSomething(int i) {
        switch(i) {
          case 0:
            // ...
            break;
          case 1:
            // ...
            break;
          case 2:
            // ...
            break;
          case 3:
            // ...
            break;
          default:
            // ...
            break;
        }
      

        Attachments

          Issue Links

            Activity

              People

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

                Dates

                Created:
                Updated: