Published on by

Not a single day goes by that I don't cringe when I see how some people write logic expressions in the code.

Consider the following typical code snippet which can probably be found in almost any project from small utility to linux kernel driver:

int func1(int param)
{
    switch (param) {
    case 0:
        set(DEVICE, 0);
        break;
    case 1:
        set(DEVICE, 1);
        break;
    case 2:
        set(DEVICE, 2);
        break;
    case 3:
        set(DEVICE, 3);
        break;
    default:
        return 1;
    }

    return 0;
}

If you are a seasoned developer you will immediately notice that it suffers from copy-paste programming syndrome. It can be rewritten like this:

int func2(int param)
{
    switch (param) {
    case 0:
    case 1:
    case 2:
    case 3:
        set(DEVICE, param);
        break;
    default:
        return 1;
    }

    return 0;
}

This eliminates three copies of duplicated code (push/call sequence), and a ton of conditional branches. Still, using switches like that is better suited for checking of larger, non-contiguous ranges of acceptable input parameters.

It can also be rewritten like this:

int func3(int param)
{
    if (param < 0 || param > 3) {
        return 1;
    }

    set(DEVICE, param);

    return 0;
}

Of course, most optimizing compilers nowadays will generate identical code for func2() and func3(), but func3() is still shorter to write, more readable, and less error-prone.