Whereas expressions may be evaluated anywhere in Squeak (for example, in a workspace, in a debugger, or in a browser), methods are normally defined in a 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 Squeak.)
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.)
Here is the method
lineCount in the class
String. (The usual convention is to refer to methods as ClassName\(\gg\)methodName, so we call this method String\(\gg\)lineCount.)
String»lineCount "Answer the number of lines represented by the receiver, where every cr adds one line." | cr count | cr := Character cr. count := 1 min: self size. self do: [:c | c == cr ifTrue: [count := count + 1]]. ↑ count
Syntactically, a method consists of:
- the method pattern, containing the name (i.e.,
lineCount) and any arguments (none in this example);
- comments (these may occur anywhere, but the convention is to put one at the top that explains what the method does);
- declarations of local variables (i.e.,
- any number of expressions separated by dots; here there are four.
The evaluation of any expression preceded by a \(\uparrow\) (typed as ^) will cause the method to exit at that point, returning the value of that expression. A method that terminates without explicitly returning some expression will implicitly return
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.