Object literals vs pattern matching or alternatives?

Gonza
Fri, 03 Nov 2023 16:39:10 +0000
Questions / Help

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?

17 posts - 4 participants