Review this function. Is it too complex?
← Getting Started · Ref: Q1030
Yes, this function is too complex. It does three things: validates input, calculates a result, and formats output. Each concern should be a separate pure function.
Split into:
- validateInput: checks if the values are usable
- calculateTotal: does the arithmetic
- formatResult: converts to a display string
Benefits:
- Each function is testable in isolation
- Pure functions can be reused elsewhere
- The main function becomes a pipeline of clear steps
- Complexity is distributed across small, readable units
EK9 encourages small pure functions composed together. When a function has multiple responsibilities, split it.
Example
defines module qa.gettingstarted.reviewcomplexity defines function validateAmount() as pure -> amount as Float <- rtn as Boolean: amount? calculateWithTax() as pure -> amount as Float taxRate as Float <- rtn as Float: amount + (amount * taxRate) formatCurrency() as pure -> amount as Float <- rtn as String: `Total: ${amount}` defines program ComplexityDemo() stdout <- Stdout() amount <- 99.50 taxRate <- 0.20 if validateAmount(amount) total <- calculateWithTax(amount, taxRate) stdout.println(formatCurrency(total)) else stdout.println("Invalid amount")
Common mistakes
E11031 — 'value' is a banned non-descriptive variable name in EK9 — use a meaningful identifier such as 'total'. See ek9 -h E11031 for details.
Incorrect:
value <- calculateWithTax(amount, taxRate)
stdout.println(formatCurrency(value))
Correct:
total <- calculateWithTax(amount, taxRate)
stdout.println(formatCurrency(total))
Other ways to ask this
- Is this code doing too much in one function?
- Should I break this function into smaller pieces?
- Assess the complexity of this EK9 function
Coming from another language?
EK9 encourages small, pure functions composed together. Split complex functions into single-responsibility pieces.
Keywords: pure, function, review, complexity, split