Refactoring many OR statements like a ninja 🀘

Marcos Henrique - Jan 26 '20 - - Dev Community

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`);
}
Enter fullscreen mode Exit fullscreen mode

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`);
}
Enter fullscreen mode Exit fullscreen mode

In C# πŸ±β€πŸ’»

if (new List<string> {"πŸ“", "🐦", "🐧", "πŸ¦‰"}.Contains(animal)) {
  System.Diagnostics.Debug.WriteLine("I'm bird, pew pew")
}
Enter fullscreen mode Exit fullscreen mode

In Python 🐍

if animal in ["πŸ“", "🐦", "🐧", "πŸ¦‰"]:
  print "I'm bird, pew pew"
Enter fullscreen mode Exit fullscreen mode

In Clojure πŸ€“

(if (string/includes? ["πŸ“", "🐦", "🐧", "πŸ¦‰"] #animal)
  (println "I'm bird, pew pew"))
Enter fullscreen mode Exit fullscreen mode

In Elixir 🍷

if Enum.member?(["πŸ“", "🐦", "🐧", "πŸ¦‰"], animal) do
  IO.puts "I'm bird, pew pew"
Enter fullscreen mode Exit fullscreen mode

Much more elegant isn't it?
🍻

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player