Plan a refactoring to improve this code. What EK9 constructs should I use?

← Getting Started · Ref: Q1037

Refactoring plan using EK9 constructs:

1. Extract pure functions for each calculation:

   Move validation and computation into separate pure functions. Pure functions are easier to test and can be reused in stream pipelines.

2. Replace loops with stream pipelines:

   If you are filtering or transforming a collection, use:
     cat items | filter by predicate | map with transform | collect as List of T
   Streams express intent more clearly than loops.

3. Use switch expressions instead of if-else chains:

   switch value
     case 1
       handleOne()
     case 2, 3
       handleFewCases()
     default
       handleOther()
   Multiple case values on one line replace fallthrough.

4. Use guard expressions for conditional logic:

   if result <- computeSomething()
     process(result)
   Guards combine computation and null-safety checking.

5. Use records for data transfer:

   Records give you automatic operators (equality, string representation, hashcode) with no boilerplate.

Priority order: extract pure functions first, then replace loops with streams, then clean up conditionals.

Example

defines module qa.gettingstarted.planrefactor

  defines function

    isValid() as pure
      -> price as Float
      <- rtn as Boolean: price?

    applyMarkup() as pure
      -> price as Float
      <- rtn as Float: price * 1.20

    formatPrice() as pure
      -> price as Float
      <- rtn as String: `Price: ${price}`

  defines program

    RefactorDemo()
      stdout <- Stdout()

      prices <- [10.0, 25.50, 0.0, 42.99]

      //Stream pipeline: validate, transform, format, output
      cat prices
        | filter by isValid
        | map with applyMarkup
        | map with formatPrice
        > stdout

Common mistakes

E11031 — 'value' is a banned non-descriptive variable name in EK9 — use a meaningful identifier like 'price'. See ek9 -h E11031 for details.

Incorrect:

      -> value as Float
      <- rtn as String: `Price: ${value}`

Correct:

      -> price as Float
      <- rtn as String: `Price: ${price}`
Other ways to ask this
  • How should I refactor this procedural code into idiomatic EK9?
  • What is the EK9 way to restructure this code?
  • Plan an EK9 refactoring with specific construct recommendations

Coming from another language?

EK9 refactoring prioritises pure function extraction, stream pipeline adoption, and guard expressions.

Keywords: switch, plan, pure, stream, guard, refactor