Extract to Localized Text

Extract to Localized Text moves a hard-coded string out of the code and into a localized text method, rewriting the call site to use the text variable already in scope. Here "Goodbye for now!" is hard-coded in ShowFarewell, when appText - the AppText text type's en_GB instance - already speaks for this module. To play it in the IDE: Help > Lessons > Refactoring…, or ek9 -ide -lesson extract-to-localized-text.

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

  defines text for "en_GB"

    AppText
      welcome()
        -> name as String
        `Hello, ${name}!`

  defines program

    ShowFarewell()
      stdout <- Stdout()
      appText <- AppText("en_GB")
      stdout.println(appText.welcome("Steve"))
      stdout.println("Goodbye for now!")

//EOF

Step 1: Where it is

Put the caret on "Goodbye for now!", on line 17.

The EK9 IDE once this is done: Put the caret on "Goodbye for now!", on line 17

Step 2: Extract to Localized Text

Right-click it - or choose Refactor > Refactor This… - and choose Localisation > Extract to Localized Text…

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

Name the new method farewell, and the text variable it is called on, appText - already in scope here. AppText is the module's only text type, so it is chosen already. Choose Preview.

The EK9 IDE just before choosing Preview: Name the new method farewell, and the text variable it is called on, appText - already in scope here

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 to Localized Text: "Goodbye for now!" is gone from ShowFarewell, and AppText gained farewell() - one method, one body, for its one locale. A text type spanning several locales instead gets a stub per locale, listed for translation; a literal with no text type yet needs Code > Localisation > New Text Type… first. It is on the right-click menu wherever the caret sits in a string literal that is not part of a + chain - that is Rewrite String Concatenation's job instead; AI assistants use the ek9_extract_to_localized_text tool.

The EK9 IDE when the lesson has finished

Where this lesson comes from