Extract Method

Extract Method moves a block of statements into a function of its own, called where the block was. Here seven ifs inside each other are too deep to follow, so EK9 refuses it - E11011, explained in the Hovers panel; moving the inner four into a function of their own brings both under the limit. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson extract-method.

The EK9 IDE as the lesson opens: the code to read and, in the Hovers panel, its error explained

Start from

The code the lesson starts from: copy it into a file of your own and follow the steps.

Fails with E11011: excessive nesting - extract function

#!ek9
defines module error.e11011.bad

  defines constant
    LEVEL_TWO <- 2
    LEVEL_THREE <- 3
    LEVEL_FOUR <- 4
    LEVEL_FIVE <- 5
    LEVEL_SIX <- 6

  defines function

    deepSimpleNesting()
      -> mainValue as Integer
      stdout <- Stdout()
      if mainValue > 0
        if mainValue > 1
          if mainValue > LEVEL_TWO
            if mainValue > LEVEL_THREE
              if mainValue > LEVEL_FOUR
                if mainValue > LEVEL_FIVE
                  if mainValue > LEVEL_SIX
                    stdout.println(`${mainValue} is above every level`)

Step 1: The statements

Select from if mainValue > LEVEL_THREE, on line 19, to the end of the line with stdout.println, line 23.

The EK9 IDE once this is done: Select from if mainValue > LEVEL_THREE, on line 19, to the end of the line with stdout.println, line 23

Step 2: Extract Method

Choose Refactor > Extract Method…

The EK9 IDE once this is done: Choose Refactor > Extract Method…

Name it reportHighLevels - what the block does - and choose Preview.

The EK9 IDE just before choosing Preview: Name it reportHighLevels - what the block does - and choose Preview

Step 3: Preview and apply

The preview shows every change the refactoring makes; then the IDE formats each file it changed. Choose Apply.

The EK9 IDE just before choosing Apply: The preview shows every change the refactoring makes; then the IDE formats each file it changed

The result

That is Extract Method: the inner four ifs are reportHighLevels, called where they were, with mainValue and stdout passed in - seven levels became three here and four there. Cmd+Option+M opens it (Ctrl+Alt+M elsewhere); AI assistants use the ek9_extract_method tool.

The EK9 IDE when the lesson has finished

Where this lesson comes from