My function is too complex and the compiler rejects it. How do I refactor to reduce complexity?

← Code Quality · Ref: Q1020

EK9 enforces complexity limits at compile time. If your function exceeds the threshold, extract smaller named functions.

TECHNIQUES:

1. EXTRACT GUARD FUNCTIONS

Before: one function with 5 conditions
After: 5 small pure functions, each checking one condition, called from a simple pipeline or sequence

2. USE STREAM PIPELINE

Before: nested for loop with if/else inside
After: cat source | filter by condition | map with transform | collect
Each pipeline operation is a separate function — complexity distributed across small functions

3. USE SWITCH EXPRESSION

Before: chain of if/else-if/else-if
After: switch with case clauses — switch is a single control flow construct, lower complexity than chained if/else

4. EXTRACT HELPER FUNCTIONS

Before: one long function doing 3 things
After: 3 named functions called in sequence — each under the limit

The compiler counts branches (if, else, case, catch, for, while) per function. Keep each function focused on one task.

Example

defines module qa.codequality.refactorcomplexity

  defines function

    //BEFORE: complex condition inline
    //isEligible <- age > 18 and score > cutoff and active and not suspended
    //This contributes 4 branches to the containing function

    //AFTER: extract each check into a named function
    isAdult() as pure
      -> age as Integer
      <- rtn as Boolean?
      adultAge <- 18
      rtn: age > adultAge

    meetsScoreThreshold() as pure
      ->
        score as Integer
        cutoff as Integer
      <- rtn as Boolean: score > cutoff

    isActiveAccount() as pure
      -> active as Boolean
      <- rtn as Boolean: active

  defines program

    RefactorDemo()
      stdout <- Stdout()

      age <- 25
      score <- 85
      cutoff <- 70
      active <- true

      //Clean: each check is a named function
      eligible <- isAdult(age) and meetsScoreThreshold(score, cutoff) and isActiveAccount(active)
      stdout.println(`Eligible: ${eligible}`)
Other ways to ask this
  • How do I fix a complexity error in EK9?
  • What techniques reduce cyclomatic complexity in EK9?
  • The compiler says my method exceeds the complexity limit. How do I split it?

Coming from another language?

EK9 enforces complexity limits at compile time. Extract small pure functions and use stream pipelines to distribute complexity.

Keywords: complexity, cyclomatic, limit, quality, refactor, extract