First programming lesson: Control structures. Senior developer lesson: avoid them.
TL;DR: Don use Ifs or its friends
-
Too many decisions together
-
Coupling
-
Duplicated code
-
Violation of Open/Closed Principle.
-
A new condition should not change the main algorithm.
-
Nulls
-
Polymorphism
-
Create hierarchies/compose objects following Open closed principle.
-
Use State pattern to model transitions.
-
Use Strategy Pattern/Method Object to choose for branches.
-
Discrete Values
-
State transition
-
Algorithm choice.
class Mp3Converter {
convertToMp3(source, mimeType) {
if(mimeType.equals("audio/mpeg")) {
this.convertMpegToMp3(source)
} else if(mimeType.equals("audio/wav")) {
this.convertWavToMp3(source)
} else if(mimeType.equals("audio/ogg")) {
this.convertOggToMp3(source)
} else if(...) {
// Lots of new clauses
}
class Mp3Converter {
convertToMp3(source, mimeType) {
const foundConverter = this.registeredConverters.
find(converter => converter.handles(mimeType));
// Do not use metaprogramming to find and iterate converters
// since this is another problem.
if (!foundConverter) {
throw new Error('No converter found for ' + mimeType);
}
foundConverter.convertToMp3(source);
}
}
#Detection
Since there are valid cases for If/else usages, we should not pull the plug and forbid these instructions. We can put a ratio of if statements/other statements as a warning instead.
Code Smell 110 - Switches With Defaults
Code Smell 133 - Hardcoded IF Conditions
How to Get Rid of Annoying IFs Forever
Photo by Adarsh Kummur on Unsplash
If debugging is the process of removing software bugs, then programming must be the process of putting them in.
Edsger Dijkstra
Software Engineering Great Quotes
This article is part of the CodeSmell Series.