Previous Page
Next Page

6.15. Multipart Selections

Avoid cascading an if.

Avoid cascades of if-elsif-elsif-else statements wherever possible. They tend to produce code with poor readability that is also expensive to execute.

The readability of an if cascade suffers because the blocks associated with each alternative have to be placed between the alternatives themselves. That can easily cause the entire construct to expand beyond a single screen or page. Any kind of code that extends over a visual boundary is very much more difficult to understand, because the reader is then forced to mentally cache parts of the construct as they scroll through it.

Even if the code doesn't cause a mental page fault, the alternation of condition-action-condition-action-condition-action can make it difficult to compare the conditions and hence to verify that the logic you're implementing is correct. For example, it can be hard to verify that, collectively, your conditions cover all the important alternatives. It can also be difficult to ensure that they are mutually exclusive.

Likewise, if the actions are very similar (e.g., assigning different values to the same variable), it's relatively easy to induce errors (mistyping the variable name in one branch, for example) or to introduce subtleties (such as deliberately using a different variable name in one branch).

The performance of an if cascade can also be suboptimal. Unless you are able to put the most common cases first, a cascaded if is going to have to test, on average, one-half of its alternative conditions before it can execute any of its blocks. And often it's simply not possible to put the common cases first, either because you don't know which cases will be the common ones or because you specifically need to check the special cases first.

The following guidelines examine specific types of cascaded if, and suggest alternative code structures that are more robust, readable, and efficient.

    Previous Page
    Next Page