Wednesday, August 14, 2013

Flatten nested if statements with the opposite condition

Have you ever found yourself nesting if, for and other flow-control statements seemingly endlessly into the dreaded arrow formation?
EG:
if this:
    if that:
        for x in X:
            if yuck:
                ...
            else:
                ...
                continue
    else:
        while Y:
            if foobar:
                ...
            else:
                ...
                break
else:
    ...
One of the easiest ways to collapse if statements is using the opposite condition and return, continue or break.
EG:
if not this:
    ...
    return
if not that:
    while Y:
        if not foobar:
            ...
            break
        ...
    return
for x in X:
    if not yuck:
        ...
        continue
    ...
Some refactoring tools will help you do this, but it good programming practice to avoid nested flow-control statements when possible. Even though in this case it only eliminated 2 lines, it is more compact, lines are not as long, so wrapping/continuing/splitting commands is not an issue, and in general the code should run faster, since it only executes as much code as is needed before returning, continuing or breaking.

No comments:

Post a Comment

Fork me on GitHub