Gonza

Gonza

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?

Showing Posts 1 to 10

sodapopcan

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.

Gonza

Gonza OP

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

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

sodapopcan

Just adding that your fall-through clause should probably be def thing_do(nil), do: # ... otherwise you could run into some subtle bugs. Since _ will match anything, thing_do(:thang_tree), for example, will successfully hit the default clause. You probably want things to just blow up in that case.

Gonza

Gonza OP

Thanks for the input! That’s a subtle difference, yes, worthy of consideration.
In my particular case, I guess I’d usually just use _ because I’d want to catch all other cases and send them to a virtual black hole. In an express controller, for example, I do something like DEFAULT: () => res.json({success: false, code: 'UNKNOWN_PARAM'}) (just ignore the fact I’m supposed to check beforehand my flags, it’s just an example)
But I see the value in treating nil as a different thing too

sodapopcan

sodapopcan

Yep, I didn’t mean to say you must do it, just consider it :slight_smile: I have a general problem with wording on this site (and in general) :sweat_smile:

Gonza

Gonza OP

Yeah, don’t worry! English is not my native language so I understand when people say they have a problem with words lol. Sometimes I can’t brain either.

sodapopcan

sodapopcan

Unfortunately it is my first language :sweat_smile:

In any event, welcome to Elixir Forums!

derek-zhou

derek-zhou

I’d question the wisdom of pattern matching on nothing but an atom. Seems like unnecessary polymorphism to me. It would had made more sense if there is a tagged record, ie: {:thing_one, some_data}. Just an atom? Where does it come from?

sodapopcan

sodapopcan

Interesting. I don’t know OP’s exact usecase, though I’ve worked on code matching on atoms before. In that case it was mapping well-known atoms to modules. It was basically just a map but using a function to get around compile-conflicts. The atoms came from database strings (I did not design that code and wasn’t there very long, lol). In this case, OP seems to essentially want a map with executable keys, so I think this is ok? If we’re talking about message passing then ya, a single atom probably isn’t very useful. But ya, there might be an even better solution for what OP is after, I just didn’t dig as I didn’t feel up to XY’ing today :upside_down_face:

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews