‘switch’ statements should not be nested

Why you should care

Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.

How we detect

CAST Highlight counts one occurrence each time a nested switch is encountered.

Bad Code

switch (n) {
case 0:
switch (m) { // Noncompliant; nested switch
case 0:
// ...
case 1:
switch (o) { // Noncompliant; nested switch

case 0:
switch (p) { // Noncompliant; nested switch
//...
}

default:
// ...
}
}
case 1:
switch (o) { // Noncompliant; nested switch
default:
// ...
}
default:
// ...
}

Good Code

function foo(n: number, m: number) {
  switch (n) {
    case 0:
      bar(m);
    case 1:
      // ...
    default:
      // ...
  }
}
 
function bar(m: number) {
  switch(m) {
    // ...
  }
}

References

5362

About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.