Ada 95 Quality and Style Guide Chapter 5

Chapter 5: Programming Practices - TOC - 5.6 STATEMENTS

5.6.1 Nesting

guideline

• Minimize the depth of nested expressions (Nissen and Wallis 1984).
• Minimize the depth of nested control structures (Nissen and Wallis 1984).
• Try using simplification heuristics (see the following Notes).

• instantiation

- Do not nest expressions or control structures beyond a nesting level of five.

example

The following section of code:

```if not Condition_1 then
if Condition_2 then
Action_A;
else  -- not Condition_2
Action_B;
end if;
else  -- Condition_1
Action_C;
end if;
```

can be rewritten more clearly and with less nesting as:

```if Condition_1 then
Action_C;
elsif Condition_2 then
Action_A;
else  -- not (Condition_1 or Condition_2)
Action_B;
end if;
```

rationale

Deeply nested structures are confusing, difficult to understand, and difficult to maintain. The problem lies in the difficulty of determining what part of a program is contained at any given level. For expressions, this is important in achieving the correct placement of balanced grouping symbols and in achieving the desired operator precedence. For control structures, the question involves what part is controlled. Specifically, is a given statement at the proper level of nesting, that is, is it too deeply or too shallowly nested, or is the given statement associated with the proper choice, for example, for if or case statements? Indentation helps, but it is not a panacea. Visually inspecting alignment of indented code (mainly intermediate levels) is an uncertain job at best. To minimize the complexity of the code, keep the maximum number of nesting levels between three and five.

- Can some part of the expression be put into a constant or variable?
- Does some part of the lower nested control structures represent a significant and, perhaps, reusable computation that I can factor into a subprogram ?
- Can I convert these nested if statements into a case statement?
- Am I using else if where I could be using elsif ?
- Can I reorder the conditional expressions controlling this nested structure?
- Is there a different design that would be simpler?

exceptions

If deep nesting is required frequently, there may be overall design decisions for the code that should be changed. Some algorithms require deeply nested loops and segments controlled by conditional branches. Their continued use can be ascribed to their efficiency, familiarity, and time-proven utility. When nesting is required, proceed cautiously and take special care with the choice of identifiers and loop and block names.

 < Previous Page Search Contents Index Next Page >
 1 2 3 4 5 6 7 8 9 10 11 TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC TOC
 Appendix References Bibliography