Gonza
Object literals vs pattern matching or alternatives?
Hi! Quick question from a guy coming from Javascript:
Whenever I have to handle some conditional behavior, like ‘do something depending on a well-defined flag’, instead of using a switch/case construct or a bunch of if/else, I usually do something like this:
const thingDoers = {
thingOne: () => { /* do thing one */ },
thingTwo: () => { /* do thing two */ },
thingThree: () => { /* do thing three */ },
DEFAULT: () => { /* do default thing */ }
}
Then I just run thingDoers[flag || 'DEFAULT']() and it works for all cases. If I have to add an additional one, is just a matter of declaring a new function, no extra logic involved.
Is this an acceptable/common pattern in Elixir as well, or do we just pattern-match the thing? Is there a better / more idiosyncratic way of doing the same?
Marked As Solved
sodapopcan
Definitely pattern match.
This is a nice use of multi-head functions AFAIC:
def thing_do(:thing_one), do: # ...
def thing_do(:thing_two), do: # ...
def thing_do(:thing_three), do: # ...
def thing_do(_), do: # ...
thing_do(flag) # If `flag` is `nil` it'll hit the last (default) case
You can do the same thing with one function head and a case if you want. It’s the same thing at the end of the day.
Also Liked
Gonza
Thanks! Looks even cleaner (my main driver for rejecting switch/case and nested ifs)
I’m still learning about Elixir but I’m loving it every day a little more
sodapopcan
Definitely don’t shy away from case! It’s very commonly used in Elixir. It’s much different than JS’s switch since it deals exclusively with pattern matches (and of course doesn’t need to break).
sodapopcan
Last Post!
Gonza
Oh sorry, it was more like a theoretical question. I’m learning Elixir and while I do, I usually think about how I would reimplement my existing codebase in an idiosyncratic way on Elixir.
So remembering syntax off the top of my head (sorry for any mistake), it’d be like this:
def do_thing %{:thing_one, payload} do: thing_one_handler payload
def do_thing %{:thing_two, payload} do: thing_two_handler payload
def do_thing %{:thing_three, payload} do: thing_three_handler payload
def do_thing _ do: default_handler
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #hex
- #security









