DEV Community

Cover image for Refactoring many OR statements like a ninja 🤘

Refactoring many OR statements like a ninja 🤘

wakeupmh profile image Marcos Henrique ・1 min read

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?


Editor guide
jasterix profile image

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

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