Co[de]mmunications

Programming and ramblings on software engineering.

Readable Logic

Compare

if (!device || !this.launched) {
    abort();
}
else {
    run();
}

with

if (device && this.launched) {
    run();
}
else {
    abort();
}

Chances are, you are wired to parse the second version faster. Make it a habit to see if your code’s readability can be improved by avoiding negations.

Nesting can also improve readability.

if (a) {
    doFirstThing();
}
if (a && b) {
    doSecondThing();
}
if (!a && b) {
    doThirdThing();
}

versus

if (a) {
    doFirstThing();
    if (b) {
        doSecondThing();
    }
}
else {
    if (b) {
        doThirdThing();
    }
}

The best logic of all is no logic. Compare

if (person.isChild) {
    run();
}
else if (person.isBaby) {
    crawl();
}
else if (person.isSenior) {
    sit();
}
else {
    walk();
}

with a data-driven approach

var groupAction = {
    children: run,
    babies: crawl,
    seniors: sit
}

var action = groupAction[person.group] || walk;
action();

Comments