DEV Community

Cover image for Refactoring many OR statements like a ninja 🤘
Marcos Henrique
Marcos Henrique

Posted on

Refactoring many OR statements like a ninja 🤘

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?
🍻

Top comments (1)

Collapse
 
jasterix profile image
Jasterix

Great article. For the JavaScript block, where/how are you defining animal?

if (['🐓', '🐦', '🐧', '🦉'].includes(animal)) {
  console.log(`I'm bird, pew pew`);
}