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
?