Tiny Tip for Elixir Case Conditions

Disclaimer: this piece of knowledge might be a flag that you need to restructure your code, but knowledge is power so there you have it.

Sometimes, when you write a multiple codition block in elixir you find yourself having more than 1 condition lead to the same result, turning your code into something like this:

case role do
  "admin" -> give_power()
  "developer" -> give_power()
  "regular_user" -> dont_give_power()
end

It’s a bit annoying how 2 of the conditions lead to the exact same result, isn’t it? Fear not though, I’ve got just the hack for you: guards!

case role do
  n when n in ["admin", "developer"] -> give_power()
  "regular_user" -> dont_give_power()
end

Basically, with the help of guards you gain the power of rewriting the condition however you want and avoid duplicates! Isn’t that awesome?!

Alexandra Docolin

Developer. React-Native worshipper. Please don't ask me about tests 😊

Tags
Elixir