DEV Community

Discussion on: Which would you prefer and why?

Collapse
 
dallgoot profile image
dallgoot

Let's split on the principles that describe the needs:

  • function checks 'arg' value among known values (implies constants)
  • function then process a treatment according to that value
  • if the value is unknown/invalid : fallback or error
function onOption(arg) {
    switch (arg) {
        case OPTION1 : return onOption1();
        case OPTION2 : return onOption2();
        case OPTION3 : return onOption3();
        default:
            return onUnknownOption()
    }
}

Results:

  • the accepted values are used through constants: consistency through code and a single place for modifications if need to be.
  • The function do a simple thing : branching against 'arg' value according to a set of known values (unless invalid).
  • Every specific process is encapsulated in a specific function: if a treatment is shared between option : another function can encapsulate it and make it reusable, where if it were inside the switch it would mean copy/pasting (or worse trying to factorize using IF). If "onOptionX" methods are pure, this is a pure function also.

I see often people trying to replace a switch with an object.
On the eye it's pleasant but in reality it's not using the simplest language construct to do the job, it's allocating memory for an object only to perform a string comparison.
Moreover many people don't take in account the "key not found" scenario leading to functions that errors or return undefined.