DEV Community

Discussion on: A New Coding Style for Switch Statements in JavaScript/TypeScript

Collapse
 
chiangs profile image
Stephen Chiang

I prefer a variation of what you have. This is what I do in my reducers and I think it translates well in components.

I feel that this has 3 advantages:

1st, you can easily see what's going on in the switch statement and go from there.

2nd, by returning, you don't have to worry about missing a break;

3rd, essentially they are different processes and entry may have the same name, but may or may not differ in type for custom and basic...or if implementations for processing them them may change this will allow you to easily update that with separated functions.

const basicProcess = (id) => {
  const entry = getBasicEntry(id);
  return doBasicProcessing(entry);
}

const customProcess = (id) => {
  const entry = getCustomEntry(id);
  return doCustomProcessing(entry);
}

switch (body.type) {
  case 'isBasic':
    return basicProcess(body.id);
  case 'isCustom': 
    return customProcess(body.id);
  default: {
    throw new Error(`Unknown flag ${myFlag}`);
  }
Collapse
 
nebrius profile image
Bryan Hughes

This is definitely my second top choice, but I prefer my other approach honestly. I really don't like functions that are 2-3 lines long, unless they're dense and hard to read. IME, having a lot of small functions strung together can get hard to follow, since you're having to jump all over the file to trace the path of execution.

To be clear though, this is not a strong preference at all, it's pretty mild, and your method is definitely my second pick :)

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

All of these solutions are great, but they could benefit from having compile-time exhaustiveness checking via the never type. I describe that here: dev.to/cubiclebuddha/is-defensive-...