December 21, 2024

Smalltalk Methods

 

All messages are associated with some Smalltalk code that is executed when a message is sent to an object. This code is called a method. Methods often contain no more than a few lines of code and take the form:

method heading
   "Initial comment"
   | temporary variable |
   method body

Here is an example, the right instance method of the Frog class

right
   "Increment position of receiver by 1. Answer the
   receiver."
   self position: ((self position) + 1)

The method heading corresponds to the message of the same name in the protocol. Consequently, in the protocol of Frog there is a message named right, with a corresponding method named right. When a Frog instance receives the message right the method right is executed.

The initial comments are important and they provide a specification for the method. So concentrate on writing a clear and concise explanation of what the code does and remember to include what message answer is returned. Although Smalltalk methods are usually quite short, comments can be placed within lengthier passages of code. This is good programming practice and helps any reader of your program to better understand the code.

One small tip. You can also comment out errors in your code. That way you can save the method before exiting the method pane to check something, either in the class browser or some other part of the Learning Book.

surfaceArea: aNumber
   "Sets the radius of the receiver to agree with the
   specified surface area. Answers the receiver."

   "self radius: ((aNumber / (4 * Float pi)) sqrt)"

   "The line above has been hidden from the
   Smalltalk parser.The method will compile with just
   the heading and intial comment in place."

Temporary variables are declared by placing them between vertical bars. They are used to provide references to objects used in the method. Smalltalk will discard them after the method has been executed.

|tempString spacer|
spacer := ' '.
tempString := 'The following items were found: '
"Rest of the code omitted"

Next page » Accessors

Previous page « Assignment

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page