ABAP Keyword Documentation → ABAP Programming Guidelines → Structure and Style → Complexity
Nesting Depth
Other versions: 7.31 | 7.40 | 7.54
Background
The nesting depth is the number of statement blocks that are nested due to the use of control structures (branches, loops). We will discuss the nesting depth at the level of a procedure (method). Implementations must not occur at other points.
The maximum nesting depth is restricted to 256 by the ABAP Compiler.
Rule
Restrict the nesting depth of control structures
Restrict the maximum nesting depth within a procedure (method) to five levels.
Details
In addition to the number of executable statements, the control structures of a procedure
(method) are also important for their clarity and traceability. Nested branches and loops
(IF
, CASE
, DO
,
WHILE, LOOP
statements, etc.) become less clear and more difficult
to trace with every nesting level. For this reason, the nesting depth must be restricted within a procedure, for example, by moving functionality to other procedures.
A maximum nesting depth of five levels is considered tolerable. A deeper nesting requires a great deal of effort to trace the program flow based on the source code. This would considerably constrain maintenance and further development.
Note
The use of modern language elements can help to restrict the maximum nesting depth. This is the case
if a statement or a predefined function replaces an entire control structure, for instance, for
REPLACE with the ALL OCCURRENCES
addition or for the numerical extremum functions, nmax(
) and nmin( )
, to determine the maximum or minimum value. The former replaces a loop, the latter an IF
control structure.
Example
The transition from the bad to the good example in the rule for modern ABAP shows how you can reduce the nesting depth by using modern language elements.