Scenario π
Let's supose we have to check which animals are bird, a Junior developer would made something like this:
if (animal === 'π' || animal === 'π¦'|| animal === 'π§' || animal === 'π¦') {
console.log(`I'm bird, pew pew`);
}
But according with Clean Code, uncle Bob if he saw this maybe would have this reaction:
Refactoring π₯³
Many ||
statements are a little too verbose and in addition have poor readability, so how we can improve this situation.
We can apply a nice concept, create an array (or list) with all comparasions and test if our animal are included on this array (or list)
Let's check some code to clarify the idea π
In javascript π
if (['π', 'π¦', 'π§', 'π¦'].includes(animal)) {
console.log(`I'm bird, pew pew`);
}
In C# π±βπ»
if (new List<string> {"π", "π¦", "π§", "π¦"}.Contains(animal)) {
System.Diagnostics.Debug.WriteLine("I'm bird, pew pew")
}
In Python π
if animal in ["π", "π¦", "π§", "π¦"]:
print "I'm bird, pew pew"
In Clojure π€
(if (string/includes? ["π", "π¦", "π§", "π¦"] #animal)
(println "I'm bird, pew pew"))
In Elixir π·
if Enum.member?(["π", "π¦", "π§", "π¦"], animal) do
IO.puts "I'm bird, pew pew"
Much more elegant isn't it?
π»
Top comments (1)
Great article. For the JavaScript block, where/how are you defining
animal
?