Extract Trait

Extract Trait pulls a class's public methods out into a NEW trait it then implements: the class keeps its bodies, gains 'with trait of' and the new trait's name on its header and 'override' on each extracted method. Here Product's describe() is the kind of thing other things in a catalogue could promise too, without being a Product. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson extract-trait.

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.inventory

  defines class

    Product
      name as String: String()

      Product() as pure
        -> productName as String
        name :=? String(productName)

      describe() as pure
        <- rtn as String: `Product: ${name}`

      default operator ?

  defines program

    Inventory()
      stdout <- Stdout()
      product <- Product("Widget")
      stdout.println(product.describe())

//EOF

Step 1: Where it is

Put the caret on Product, on line 6.

The EK9 IDE once this is done: Put the caret on Product, on line 6

Step 2: Extract Trait

Right-click it - or choose Refactor > Refactor This… - and choose Extract Trait…

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

Name it Describable - what describe() promises - and choose Preview.

The EK9 IDE just before choosing Preview: Name it Describable - what describe() promises - 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 Trait: Product now implements Describable, describe() is overridden, and the trait declares describe() as abstract for anything else that adopts it. A name already used in the file, or a method that is private, protected or an operator, surfaces as a conflict instead of an error (traits are public-only, E07270). It is on the right-click menu wherever the caret is on a class's declaration line with at least one extractable method; AI assistants use the ek9_extract_trait tool.

The EK9 IDE when the lesson has finished

Where this lesson comes from