Some useful conditional branches conversions

I collected a small number of conditional branching conversions which offer some benefits.

Case 1.

If you turn this:


if(expr1) {
    code1;
}
else if(expr2) {
    code2;
}
else {
    code3;
}

into this:


if(expr1) {
    code1;
}
else {
    if(expr2) {
        code2;
    }
    else {
        code3;
    }
}

than it is handier to test expr2 for timing, correctnes, etc.

Case 2.

If instead of this:


if(!expr1) {
    code1;
}
if(expr1) {
    if(expr2) {
        code1;
    }
    else {
        code2;
    }
}

you write this:


if(expr1 && !expr2) {
    code2;
}
else {
    code1;
}

you can avoid duplicating same code (code1) while making a branch simpler and more readable.

Case 3.

If instead of this:


if(expr1) return value1;
else if (expr2) return value2:
else if (expr3) return value3;
else return value4;

you write:


if(expr1) return value1;
if(expr2) return value2:
if(expr3) return value3;
return value4;

Then ... I don't know what you really gain, but it is aligned nicer and there is one branch less (last else).

Case 4.

If you have an some code3 that if expr1 is true, it should happen after code2, which must happen either if expr2 or expr1 and after code1, but just once (does this generalize at all??), you could write like this:


if(expr1) { code1; }
if(expr2 || expr1) { code2; }
if(expr1) { code3; }

Or you could loose a branch and make it so much more readable that you will even understand what the problem was in the first place, but for the cost of copy/pasting code2 twice:


if(expr1) {
    code1;
    code2;
    code3;
}
else if(expr2) {
    code2;
}


Previous: How to synchronize working folders between different drives and computers
Next: How would a time machine influence computability