Element nesting places one control-flow structure inside another. It matters because deeper nesting increases the number of relationships and execution paths a reader must track, raising cognitive load even when traditional branch counts remain unchanged. section 3.1.2
Use nesting as a practical signal when assessing code complexity:
- Cyclomatic complexity counts independent execution paths created by decisions such as if, while, and switch. section 3.1.2
- Cognitive complexity adds weight for structures that make code harder to follow, including deep nesting and mixed logical operators. section 3.1.2
- Treat equal branch counts cautiously: differently nested methods can have very different readability costs. section 3.1.2
Nested reminder processing
A reminder method iterates over customers, evaluates activity and eligibility conditions, builds a message, sends it inside a try block, and handles an email exception. The loop, conditions, logical operators, and exception path create several relationships for the reader to hold together. section 3.1.2
Figure 3.2 Each flow-breaking structure (i.e., for, if, else) and each level of nesting increase cognitive complexity. In this example, the developer must keep track of several different execution paths to understand the overall logic.
The figure visualizes how each flow-breaking structure and each additional nesting level increases cognitive complexity. section 3.1.2
