E11021: cognitive complexity exceeds limit - extract functions

Category: E11xxx Code quality and IR analysis · Reported in phase: PRE_IR_CHECKS · Classification: COGNITIVE_COMPLEXITY · All error codes

What went wrong

Cognitive complexity measures how difficult code is to understand. Your function/method exceeds the maximum of 35.

Worked examples

Compilable examples demonstrating this error and the correct fix:

  • ek9 -q 765 (What is the cognitive complexity limit in EK9?)

[EK9-SPECIFIC FACTORS]

  • Each control structure (if, while, for, switch, try) adds cost
  • Nesting MULTIPLIES cost: depth 3 costs 3x more than depth 1
  • Declaration guards (<-) add +1 penalty per guard
  • Formula: (base_cost + guard_penalty) x nesting_depth

How to fix it

  1. Extract nested logic into helper functions
  2. Reduce nesting depth (target: 3-4 levels max)
  3. Use stream pipelines for data transformations
  4. Break up complex guard chains

See also

  • E11021: cognitive complexity (this error)
  • E11011: nesting depth limit
  • E11010: cyclomatic complexity

https://ek9.io/quality.html#complexity https://ek9.io/forAI.json#$.qualityMetrics.metrics[?(@.errorCode=="E11021")]

Examples

Every example is compiled by the EK9 compiler: the first fails exactly as captioned, the others fix it.

Fails with E11021: cognitive complexity exceeds limit - extract functions

#!ek9
defines module error.e11021.bad

  defines function

    getA()
      <- rtn as String: "a"

    getB()
      <- rtn as String: "b"

    getC()
      <- rtn as String: "c"

    getD()
      <- rtn as String: "d"

    getE()
      <- rtn as String: "e"

    getF()
      <- rtn as String: "f"

    deepGuardChain()
      <- result as String: ""

      if a <- getA()
        if b <- getB()
          if c <- getC()
            if d <- getD()
              if e <- getE()
                if f <- getF()
                  result: `${a}${b}${c}${d}${e}${f}`

Fixed: Gather the values first, then make one decision

#!ek9
defines module error.e11021.good

  defines function

    getA()
      <- rtn as String: "a"

    getB()
      <- rtn as String: "b"

    getC()
      <- rtn as String: "c"

    combined()
      <- result as String: ""
      a <- getA()
      b <- getB()
      c <- getC()
      if a? and b? and c?
        result: `${a}${b}${c}`

Questions and answers

These Q&A entries show E11021 and its fix:

Found a problem?

If EK9 reported E11021 for a program you think is valid, or did not report it where it should have, use the compiler form with the smallest program that shows it. If this page is wrong or unclear, use the documentation form. Both are at github.com/ek9lang/ek9-issues.