Generate Dispatcher

Generate Dispatcher scaffolds a dispatcher entry - 'sound() as dispatcher', say - plus one handler overload per subtype of a base type - sealed for exhaustive dispatch, or open with the entry's own fallback covering the rest. Here Animal allows only Dog and Cat; AnimalDispatcher has no dispatcher yet. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson generate-dispatcher.

The EK9 IDE as the lesson opens

Start from

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

#!ek9
defines module lesson.dispatch

  defines class

    Animal allow only Dog, Cat as open

    Dog extends Animal

    Cat extends Animal

    AnimalDispatcher

  defines program

    Show()
      stdout <- Stdout()
      processor <- AnimalDispatcher()
      stdout.println(`Dispatcher ready: ${processor?}`)

//EOF

Step 1: Where it is

Put the caret on AnimalDispatcher, on line 12.

The EK9 IDE once this is done: Put the caret on AnimalDispatcher, on line 12

Step 2: Generate Dispatcher

Right-click it - or choose Refactor > Refactor This… - and choose Generate Dispatcher…

The EK9 IDE once this is done: Right-click it - or choose Refactor > Refactor This… - and choose Generate Dispatcher…

Animal is already chosen - the workspace's one sealed type. Name the dispatcher sound and choose Preview.

The EK9 IDE just before choosing Preview: Animal is already chosen - the workspace's one sealed type

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 Generate Dispatcher: AnimalDispatcher gained sound() as dispatcher plus a private sound() overload for Dog and for Cat, each with a //AI: Implement sound lead where its body goes - exhaustive, since Animal is sealed; a non-sealed base instead leaves the entry's own fallback body to cover what has no handler. A class may hold at most one dispatcher (E07820). It is on the right-click menu wherever the caret is inside a class with no dispatcher of its own and a sealed or open base type to dispatch on; AI assistants use the ek9_generate_dispatcher tool.

The EK9 IDE when the lesson has finished

Where this lesson comes from