You abuse cases in switches and make subtle mistakes
TL;DR: Cases are GOTOs, but you might be missing them
Problems
Hidden defects
Readability
Solutions
Add the missing break
Convert the switch into a polymorphic hierarchy
Remove the default switch
Context
In a switch statement, when a match is found in a particular case, the code execution will start from that case and continue executing all subsequent cases until a break statement is encountered or the switch block ends.
This behavior is called "fall-through."
Forgetting a break clause will continue with the following case.
This is similar to a very serious vulnerability that implied an urgent release.
Sample Code
Wrong
switch (number) {
case 1:
printf("Number is 1.\n");
break;
case 2:
printf("Number is 2.\n");
// Missing break
case 3:
// Case 2 will continue here
printf("Number is 3.\n");
break;
default:
printf("Number is not 1, 2, or 3.\n");
}
// If the number is 2 this will output numbers 2 and 3
Right
switch (number) {
case 1:
printf("Number is 1.\n");
break;
case 2:
printf("Number is 2.\n");
break; // Added 'break' to prevent fall-through
case 3:
printf("Number is 3.\n");
break;
default:
printf("Number is not 1, 2, or 3.\n");
}
// This is correct even though switches AND defaults
// Are other code smells
Detection
[X] Automatic
Many linters and also ChatGPT detect this smell.
Tags
- IFs
Conclusion
Using switches and causes is problematic, your need to use higher-level sentences.
Relations
Code Smell 110 - Switches With Defaults
Maxi Contieri ・ Dec 15 '21
Code Smell 36 - Switch/case/elseif/else/if statements
Maxi Contieri ・ Nov 28 '20
More Info
How to Get Rid of Annoying IFs Forever
Maxi Contieri ・ Nov 9 '20
Disclaimer
Code Smells are my opinion.
Credits
Photo by Nikola Johnny Mirkovic on Unsplash
I am not terribly dogmatical about the goto statement. I have the uncomfortable feeling that others are making a religion out of it, as if the conceptual problems of programming could be solved by a single trick, by a simple form of coding discipline!
Edsger Dijkstra
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)