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

"switch case" clauses should not have too many lines of code

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Reduce this "[switch/CASE|CASE/WHEN]" number of lines from {} to at most {}, for example by extracting code into a [method|subroutine|function].
    • List of parameters:
      • key : max
      • Description: Maximum number of lines of code
      • Default value : 5
      • Default for PHP: 10
      • Default for T-SQL: 10
      • Type: Integer
    • Default Severity:
      Major
    • Impact:
      Low
    • Likelihood:
      High
    • Legacy Key:
      too-many-loc-in-case-clause
    • Targeted languages:
      ABAP, Cobol, JavaScript, PL/I, TypeScript
    • Covered Languages:
      C#, C, C++, Flex, Go, Java, Kotlin, Objective-C, PHP, PL/SQL, RPG, Ruby, Scala, Swift, T-SQL, VB.Net, VB6
    • Irrelevant for Languages:
      HTML, Python, XML
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      5min
    • Analysis Level:
      Syntactic Analysis
    • Analysis Scope:
      Main Sources
    • Common Rule:
      Yes
    • PMD:
      SwitchDensity

      Description

      The switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

      Noncompliant Code Example

      With the default threshold of 5:

      switch (myVariable) {
        case 0: // Noncompliant: 6 lines till next case
          methodCall1("");
          methodCall2("");
          methodCall3("");
          methodCall4("");
          break;
        case 1:
        ...
      }
      

      Compliant Solution

      switch (myVariable) {
        case 0:                  
          doSomething()
          break;
        case 1:
        ...
      }
      ...
      private void doSomething(){
          methodCall1("");
          methodCall2("");
          methodCall3("");
          methodCall4("");
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                evgeny.mandrikov Evgeny Mandrikov
                Reporter:
                freddy.mallet Freddy Mallet (Inactive)
              • Votes:
                0 Vote for this issue
                Watchers:
                1 Start watching this issue

                Dates

                • Created:
                  Updated: