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 Codeswitch (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:
// ...
}
function foo(n: number, m: number) {
switch (n) {
case 0:
bar(m);
case 1:
// ...
default:
// ...
}
}
function bar(m: number) {
switch(m) {
// ...
}
}
References
https://stackoverflow.com/questions/15931089/alternative-to-nested-switch-statements-in-java https://www.fluentcpp.com/2017/06/27/how-to-collapse-nested-switch-statements/ https://stackoverflow.com/questions/14827914/is-there-any-design-pattern-to-avoid-a-nested-switch-case https://rules.sonarsource.com/java/RSPEC-1821About 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.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_nestedswitches-switch-statements-should-not-be-nested/
https://doc.casthighlight.com/alt_nestedswitches-switch-statements-should-not-be-nested/
Comments