Review this function. Is it too complex?
← Getting Started · Ref: Q1030
Yes, a single function that validates input, calculates a result and formats output would be too complex. Each concern should be a separate pure function.
The code shown is the decomposed result:
- validateAmount: checks the value is usable
- calculateWithTax: does the arithmetic
- formatCurrency: 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") //An unset amount is rejected by the same check missingAmount <- Float() if validateAmount(missingAmount) stdout.println(formatCurrency(calculateWithTax(missingAmount, taxRate))) 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: review, function, pure, split, complexity