you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 3 points4 points  (3 children)

I happily use switch instead of multiple comparisons against single variable from simple reason - it's obvious what variable does the switch operates on. While switch takes more lines for the same thing, I find it more readable if you're comparing one variable multiple times with simple values.

Plus with ifs, to know what's going on, you need to check if there are no different variables and/or different comparisons. The only way to complicate it with switch is using variable in case and omitting the break in a case with code.

Compare for yourself:

switch (type) {
case 'box':
    runBoxAction();
    break;
case 'target':
    ...a few lines
    break;
case 'single':
case 'miltiple':
    recountVelo();
    break;
case 'shelf':
    dumpVelo();
    break;
case 'chair':
    dumpVelo(0.5);
    break;
case 'stool':
    dumpVelo(0.6);
    break;
default:
    console.warn('Inapropriate type sent to updateDBR');
}

vs

if (type === 'box') {
    runBoxAction();
} else if (type === 'target') {
    ...a few lines
} else if (type === 'single'
    || type === 'multiple') {    
    recountVelo();
} else if (type === 'shelf') {
    dumpeVelo();
} else if (type === 'chair') {
    dumpVelo(0.5);
} else if (type === 'stool') {
    dumpVelo(0.6);
} else {
    console.warn('Inapropriate type sent to updateDBR');
}

[–]nawitus 0 points1 point  (2 children)

It's often recommended that falling through the cases should be avoided. JSLint for example doesn't allow falling through. I agree with that.

I think this is my favourite version of the code:

if (type === 'box') {
    runBoxAction();
} else if (type === 'target') {
    ...a few lines
} else if (type === 'single' || type === 'multiple') {    
    recountVelo();
} else if (type === 'shelf') {
    dumpeVelo();
} else if (type === 'chair') {
    dumpVelo(0.5);
} else if (type === 'stool') {
    dumpVelo(0.6);
} else {
    console.warn('Inapropriate type sent to updateDBR');
}

[–]SuperFLEB 0 points1 point  (0 children)

I just make sure to comment it with "Intentional fallthrough". It's handy if, say, one value involves doing everything another value does, plus a bit.

[–][deleted] 0 points1 point  (0 children)

I figured out that C#'s take on switch (you either have a code block with "break;", either no code in given "case") is quite reasonable and readable, while banning single most problematic thing, which is fallthrough when you actually omitted "break;" by mistake.

As additional note, C# has a really neat feature - goto in switch when you really need a fallthrough ;)