How does EK9 enforce nesting depth limits?

← Code Quality · Ref: Q814

EK9 enforces a maximum nesting depth of 6 levels. Code nested deeper than 6 if/while/for/switch blocks triggers E11011 EXCESSIVE_NESTING at compile time.

THRESHOLD

The nesting depth threshold is 6 levels. Each control flow construct (if, while, for, switch, try) adds one level of nesting. At 7 levels, the compiler rejects the code.

WHY THIS MATTERS

Deeply nested code is hard to follow, hard to test, and correlates with bugs. Microsoft Research found that functions with nesting depth > 5 have 3x the defect rate of shallow functions.

HOW TO FIX

- Extract inner logic to separate functions
- Use guard clauses to exit early
- Use switch instead of nested if/else chains
- Consider polymorphism for type-based branching

NESTING VS COGNITIVE COMPLEXITY

Nesting depth (E11011, threshold 6) measures structural depth. Cognitive complexity (E11021, threshold 35) measures mental effort. Deep-but-simple code triggers nesting first. Shallow-but-complex code triggers cognitive first.

See Q310 for code quality overview. See Q312 for complexity metrics.

Example

defines module qa.quality.nesting.depth

  defines function

    // === AT THE BOUNDARY: 6 levels (maximum allowed) ===
    classifyDepth() as pure
      -> inputValue as Integer
      <- result as Integer: 0

      levelTwo <- 2
      levelThree <- 3
      levelFour <- 4
      levelFive <- 5

      if inputValue > 0
        if inputValue > 1
          if inputValue > levelTwo
            if inputValue > levelThree
              if inputValue > levelFour
                if inputValue > levelFive
                  result: 6

  defines program

    NestingDepthDemo()
      stdout <- Stdout()

      result <- classifyDepth(7)
      stdout.println("Depth classification: " + $result)

      shallow <- classifyDepth(1)
      stdout.println("Shallow: " + $shallow)

Common mistakes

E11011 — Adding a 7th nesting level exceeds the maximum depth of 6. Extract the inner logic to a separate function or use guard clauses. See ek9 -h E11011 for details.

Incorrect:

                if inputValue > levelFive
                  if inputValue > 6
                    result: 7

Correct:

                if inputValue > levelFive
                  result: 6
Other ways to ask this
  • What is the maximum nesting depth in EK9?
  • Why does my code fail with EXCESSIVE_NESTING?
  • How do I fix E11011 excessive nesting in EK9?

Coming from another language?

Java: SonarQube flags deep nesting as a code smell but it compiles fine. Rust: clippy warns but is suppressible. Go: cultural convention only. C#: Roslyn analyzers warn but don't block. EK9: nesting depth > 6 is a hard compiler error that cannot be bypassed.

Keywords: extract, threshold, depth, quality, nesting, complexity, E11011, refactor, guard