5.3 Method syntax

Whereas expressions may be evaluated anywhere in Cuis-Smalltalk (for example in a workspace, in a debugger, or in a browser), methods are normally defined in the System Browser window or in the Debugger. Methods can also be filed in from an external medium, but this is not the usual way to program in Cuis-Smalltalk.

Programs are developed one method at a time, in the context of a given class. A class is defined by sending a message to an existing class, asking it to create a subclass, so there is no special syntax required for defining classes. We are already farmiliar with this from previous examples.

Let’s take a another look to the method syntax when control flow is involved – our first explanation was Spacewar! States and Behaviors).

Here is the method keyStroke: in the class SpaceWar.

SpaceWar>>keyStroke: event
"Check for any keyboard stroke, and take action accordingly"
   | key |
   key := event keyCharacter.
   event isArrowUp ifTrue: [^ ships first push].
   event isArrowRight ifTrue: [^ ships first right].
   event isArrowLeft ifTrue: [^ ships first left].
   event isArrowDown ifTrue: [^ ships first fireTorpedo].
   key = $w ifTrue: [^ ships second push].
   ...

Example 5.1: SpaceWar! key stroke

Syntactically, a method consists of:

The evaluation of any expression preceded by a ^ (typed as ^) will cause the method to exit at that point, returning the value of that expression. A method that terminates without explicitly returning the value of some expression will always return the current value of self.

Arguments and local variables should always start with lower case letters. Names starting with upper-case letters are assumed to be global variables. Class names, like Character, for example, are simply global variables referring to the object representing that class.

As you might suspect from Example 2.2, Smalltalk allClasses size just sends the #allClasses message to a dictionary named Smalltalk. As with any other object, you can inspect this dictionary. You can note a case of self-reference here: the value of Smalltalk at: #Smalltalk is Smalltalk.