Search code examples
pharo

How to add a new method in Pharo?


In the Nautilus System Browser (Pharo 6) there's a right-click command to Add package... as well as Add class... and even Add protocol..., but I can't find anywhere a way to Add method....

Where is that command?


Solution

  • In Pharo, adding a method is not as explicit as the other elements. To add a new method:

    1. Select the protocol for the method, and you should see a template in the editor pane:

      messageSelectorAndArgumentNames
         "comment stating purpose of message"
      
         | temporary variable names |
         statements
      
    2. Edit this template to make a new method,

    3. Save (Right-click Accept) it using Ctrl-S.

    In fact, any time you change a method's definition (e.g., messageSelectorAndArgumentNames) and save it in the editor (Right-click Accept or Ctrl-S), it will create a new method.

    enter image description here

    For more details, see the section 1.3 of Developing a simple counter document (emphasis is mine):

    Create a method

    Now let us create the accessor methods for the instance variable count. Start by selecting the class Counter in a browser, and make sure the you are editing the instance side of the class (i.e., we define methods that will be sent to instances) by deselecting the Class side radio button.

    Create a new protocol by bringing the menu of methods protocol list. Select the newly created protocol. Then in the bottom pane, the edit field displays a method template laying out the default structure of a method. As a general hint, double click at the end of or beginning of the text and start typing your method. Replace the template with the following method definition:

    count
       "return the current value of the value instance variable"
       ^ count
    

    This defines a method called count, taking no arguments, having a method comment and returning the instance variable count. Then choose accept in the menu to compile the method.