DEV Community

Discussion on: If (all) else is complicated, switch to switch?

Collapse
 
jankapunkt profile image
Jan Küster

Little OT here. I think switches are great for revealing unexpected program flows in a multi branch szenario, which is why the exact match condition is so important.

You want your program being as deterministic as possible and therefore throw exceptions when the program deviates at any point. Switches are a nice way to do that:

f = value => {
  case 'foo':
    return stateA()
  case 'bar':
    return stateB()
  default:
    throw new Error(`No state for ${value}`)
}
Enter fullscreen mode Exit fullscreen mode

Relying on truthy/falsy for branching is a great feature of Js but can also lead to false positives / false negatives (think empty Strings, Number 0) that require much more tests than being explicit in the first place.

Collapse
 
andrewbridge profile image
Andrew Bridge

I agree with your initial point, but not necessarily that switches are the answer.

In your example, I'd probably do something like:

const states = {
    foo: stateA,
    bar: stateB
};

const f = (value) => {
    if (!(value in states)) {
        throw new Error(`No state for ${value}`);
    }
    return states[value]();
}
Enter fullscreen mode Exit fullscreen mode

...or more generically assuming things weren't as 1-to-1...

const f = (value) => {
    if (value === 'foo') {
        return stateA();
    }
    if (value === 'bar') {
        return stateB();
    }
    throw new Error(`No state for ${value}`);
}
Enter fullscreen mode Exit fullscreen mode

The second is probably the easiest to understand out of all of them (including the switch imo) so I'd probably lean towards that, but in every case, undefined behaviours are caught appropriately.