Error checking to emphasize the main flow

Too many times main flow of the program is obscured by error check.
For example, it goes like this.

bad:

    if (conditionOk()) {
        doRealWork();
    }
    else {
        sayError();
    }

Two things are wrong here.

1. The real work is indented.
2. The reason of the error is tested far away.

If you say that’s not a big deal, take a look at the next example.

bad:

    if (conditionOk1()) {
        if (conditionOk2()) {
            doRealWork();
        }
        else {
            sayError2();
        }
    }
    else {
        sayError1();
    }

You see the real work is hidden deep inside of the program. It is not
only hard to read, also hard to write: Because you wasted 8 spaces on
the left, there is only limited room to type the real work.

We can improve it by reversing the condition check.

bad:

    if (conditionNg1()) {
        sayError1();
    }
    else if (conditionNg2()) {
        sayError2();
    }
    else {
        doRealWork();
    }

I still don’t like it because the real work is indented.

My way is as follows.

good:

    // Test and reject the wrong cases.
    if (conditionNG1()) {
        sayError1();
        return;
    }
    if (conditionNG2()) {
        sayError2();
        return;
    }

    // Do the real work.
    doRealWork();

The point is to reject wrong cases one at a time to make the
condition clean, then do the real work.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s