Default means 'everything we don't know yet'. We cannot foresee the future.
TL;DR: Don't add a default clause to your cases. Change it for an exception. Be Explicit.
Problems
Coupling
Open closed principle violation
Solutions
Replace if and cases with polymorphism
Change Default code to an Exception
Context
When using cases, we usually add a default case so it doesn't fail.
Failing is always better than taking decisions without evidence.
Since case and switches are also an smell, we can avoid them.
Sample Code
Wrong
switch (value) {
case value1:
//if value1 matches the following will be executed..
doSomething();
break;
case value2:
//if value2 matches the following will be executed..
doSomethingElse();
break;
default:
//if value does not presently match the above values
//or future values
//the following will be executed
doSomethingSpecial();
break;
}
Right
switch (value) {
case value1:
//if value1 matches the following will be executed..
doSomething();
break;
case value2:
//if value2 matches the following will be executed..
doSomethingElse();
break;
case value3:
case value4:
//We currently know these options exist
doSomethingSpecial();
break;
default:
//if value does not match the above values we need to take a decision
throw new Exception('Unexpected case ' + value + ' we need to consider it');
break;
}
Detection
[X] Semi Automatic
We can tell our linters to warn us on default uses unless there's an exception.
Tags
- Fail Fast
Conclusion
Writing robust code doesn't mean we need to take decisions without evidence.
Relations
Code Smell 36 - Switch/case/elseif/else/if statements
Maxi Contieri ・ Nov 28 '20
More Info
Credits
Photo by Joshua Woroniecki on Unsplash
The cost of adding a feature isn’t just the time it takes to code it. The cost also includes the addition of an obstacle to future expansion. The trick is to pick the features that don’t fight each other.
John Carmack
Software Engineering Great Quotes
Maxi Contieri ・ Dec 28 '20
This article is part of the CodeSmell Series.
Top comments (0)