DEV Community

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

Collapse
 
lexlohr profile image
Alex Lohr

I would actually write it like this:

switch (body.type) {
  case 'isBasic':
    const basicEntry = getBasicEntry(body.id);
    console.log(`Processing basic entry "${basicEntry.name}"`);
    doBasicProcessing(basicEntry);
    break;

  case 'isCustom':
    const customEntry = getCustomEntry(body.id);
    console.log(`Processing custom entry "${customEntry.name}"`);
    doCustomprocessing(customEntry);
    break;

  default:
    throw new Error(`Unknown flag ${myFlag}`);
}

because different things warrant different variable names.

But if you cannot come up with different names, maybe these aren't actually different things and you should aim to solve the issue with a unified approach that doesn't even require a switch statement.

Collapse
 
nebrius profile image
Bryan Hughes

I don’t agree with this, for three reasons:

1) there are more possibilities than things are the same or are different. It’s also possible, as is the case here, that they are mostly, but not completely, the same

2) we use short-hand variables all the time that are repeated. How many callbacks have err as the first argument? Are these all the same thing? No. But we do it anyways and we consider that a best practice.

3) crafting a unified approach for this sort of case would require extra boilerplate, resulting in an over-engineered solution that obfuscates what’s actually going on.

Collapse
 
lexlohr profile image
Alex Lohr

1) Actually, that things are either handled the same or different is a literal dilemma without a middle ground. So in the context of their current handling they are either identical or different, regardless of their other similarities.

2) using the same shorthands twice in the same context is a recipe for confusion unless they actually mean the exactly same thing.

3) That's why I asked this as an open question. If things are actually so similar that you can handle them without too many extra cases, you should obviously do so – and if not, your variable names should reflect the difference.

Thread Thread
 
nebrius profile image
Bryan Hughes

I still disagree, for the reasons I stated above. I think we’ll just have to agree to disagree, but thank you for sharing your perspective!

Thread Thread
 
lexlohr profile image
Alex Lohr

Thanks for taking your valuable time to raise and discuss this point.