DEV Community

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

Posted on

6 1

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

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`);
}

nextjs tutorial video

Youtube Tutorial Series πŸ“Ί

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series πŸ‘€

Watch the Youtube series

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️