Tuesday, December 15, 2015

Tiny Improvements - Avoid Nested Ifs

One anti-pattern I see all the time is:

if (condition1) {
    if (condition2) {
        A();
    }
} else {
    B();
}

Okay, what the hell is supposed to happen if condition1 is true and condition2 is not? I seriously do not know. Is it meant to do B? Is it meant to do neither A or B (cause that is what it does)? The intention is incredibly unclear and it looks like it bypasses both A and B by accident. This should be rewritten as:

if (condition1 && condition2) {
    A();
} else if (!condition1) {
    B();
}

This removes confusing nested ifs and makes the underlying logic much clearer. Making this transformation can often reveal weird behavior in edge cases.

No comments:

Post a Comment