M206 Smalltalk tutorial . Variables:- Temporary, Local, Instance, Class, Global, Pseudo, Scope.

Tutorial 5. Variables



More Tutorials
C Programming Tutorial
T223

HTML Tutorial & Web Design
T170,T171 and TT180

Search this site

Home

 

Tutorials
| 1. Starting Smalltalk, and Terminology | 2. Precedence Rules | 3. Classes - Strings | 4. Class Browser | 5. Variables | 6. Error Messages | 12. Control Structures | 16. Dialogs | 23. Collection class | 39. OpenGUI |

 

Information
| Smalltalk Books | Student Software & Books | Hints & Tips | Sites | Download Smalltalk | Coloured code | Download Documents | ASCII Codes |

 

Smalltalk Index

 

 

 

Student
Licence Software
at special prices

 

Updated 15 Oct 2001

Contents

Introduction to Variables.

  • A variable is a name, a label which references an object.
    • The object that the label refers to, can be changed - it can vary - hence the name variable.
    • The object that the label refers to is said to be that variables value.
  • A variable must be declared.
    • When declared the value that the variable references is nil.
    • When declared as an instance of a class e.g. afrog :=Frog new, and clicking the create button. The object that the variable references may be automatically initialized to some specific value. If not initialized the value that variable references is nil.
      • A useful message that can be sent to objects is isNil to check the if the state of that object is still nil, answers with either true or false.
  • A variable only refers to 1 object, although that single object may contain many objects.
    • Objects of class Collection can contain several objects of various classes.
    • Objects of class ByteString can contain several objects of class Character.
  • Several variables may refer to the same object.
  • The names used for most variables
    • Must start with a lowerCase letter ( Exceptions:- Class, class-instance, and global variables start with an Uppercase letter).
    • The initial letter can be followed by any alpha numeric characters.
    • Spaces are not allowed in names. Close the space then use a single uppercase letter for the following word.
      • Examples:- aFrog, moneySterling, distanceInMetres, anAccount.
    • It is normal for the name to give some idea of the type of value that it refers to, this is not a requirement, but makes good sense.
    • Note when you look at methods in the Class Browser how the variable names used are a good clue to their value.
      • Examples:- aNumber, aString, aColour, aDirection, messageString, aBlock

There are 6 kind of variables in the M206 Open University version of Smalltalk, less in other versions.
  • Class.
  • Class -instance.
  • Global
  • Instance.
  • Local.
  • Pseudo
  • Temporary.

Top of Page


Scope

Basically all the different types of variables listed above do the same thing, they refer to objects. The difference between these types is how and where they can be assessed, i.e. how and where they are used, and how long they last for. This is referred to as the scope of the variable.

 

The scope is listed under each type of variable below.

 

Top of Page


Temporary Variables

Temporary variables can be used in the Workspace or in methods.
  • Temporary variables are declared by enclosing them in vertical bars. Additional variables are separated by a space
  • e.g. | aName aBirthDate aTelephoneNumber |
    • To obtain the vertical bar. Use the shift key with the key to the left of the Z key, on British keyboards. Note the symbol on the key is usually 2 vertical lines, one above the other.
  • Do not use a period, on the declaration line.
When used in Methods.
  • Temporary variables are declared at the start of a method right after the method heading and , comments if present.
    • The name used must be unique within the method, do not duplicate the names of instance variables, or other temporary variables.
When used in the Workspace.
  • Temporary variables are declared at the start of expression in which they are used.
    • They must be evaluated with the expression in which they are used.

Scope

  • Temporary variables can only be used in in the expression series in which they are declared.
  • Once the expression series is finished the values are forgotten.
  • If declared in a method, they can only be used in that method.

Top of Page


Local Variables

Are used in the LearningWorks Workspace and World page.
  • Local Variables are declared by evaluating a name in the workspace and clicking the Create button in the pop up window.
  • There name appears in the variable pane

Scope

Local variables can only be used in the LearningBook section in which they are created.

 

Top of Page


Instance Variables

Are only used in methods
  • Instance variables are added in the Class Browser, by
    • Selecting (or creating) the required class.
    • Click the Add button.
    • Click the an instance variable radio button.
    • Enter the required name into the pop up Dialog request: window.
    • Click OK
  • Each instance variables have 2 main methods associated with them. These methods are known as the setter and getter (or set and get) methods.
    • The getter method is the method that obtains (gets), and answers with the current value of the instance variable.
      • The getter method normally has the same name as the instance variable
    • The setter method is the method that sets (assigns) a value to the instance variable.
      • The setter method normally has the same name as the instance variable but is a keyword method and therefore has a colon after the name, no space between the name and colon.
      • Must have 1 argument, the new value for the instance variable.
      • In order to respect encapsulation, this is the only method that is allowed to assign a value to the instance variable, using the assignment operator :=
  • When accessing instance variables, use the setter and getter methods to ensure encapsulation ( M206 Chap 13).

Top of Page

Examples of instance variables and their getter and setter methods before LB-22.
Class Instance variables Getter method Setter method
Frog or Toad position position position: aNumber
Frog or Toad colour colour colour: aColour
HoverFrog height height height: aNumber
Account holder holder holder: aName
Account balance balance balance:
Account overLimit overLimit overLimit: anAmount
From LB-22 Frogs and Toads have their instance variables moved into the new abstract Amphibian class.

Scope

Instance variables can only be assessed directly from the methods of their class and subclasses of that class. Normally this is only done by the instance variable's get and set method.

 


Top of Page


Pseudo-variables

Scope

  • The pseudo-variables are self and super and are used within methods. They are rather special.
  • You can not make an assignment to pseudo-variable.
self
  • self references the reciever of message that activated the method in which it is written.
super
  • super is like self in that it references the reciever of message but it ignores the method in the current class and uses the method of the same name in the superclass.
  • It is often used within the method initialize

Top of Page


Class Variables


  • Class variables allow common sharing of information across a range of subclasses.
  • Class variables start with an upperCase letter.
    • E.g. Pi
  • Class variables are added in the Class Browser, by
    • Selecting (or creating) the required class.
    • Click the Add button.
    • Click the a class variable radio button.
    • Enter the required name into the pop up Dialog request: window.
    • Click OK
  • There are very few class variables that are of interest to you. The ones in Date and Time classes, possibly Pi, and any that you create such as FrogCountin Frog class. LB-22
  • There is a good chance of a TMA requiring a class variable, and class methods.
    • Because there are very few examples to guide you, pay particular attention to anything you do with class variables and class methods.
Three common uses for class variables are:
  • For a class to keep track of all its instances. LB-22
  • To hold constants (values that never change) E.g.
    • In Date class. The names of the months of the year, MonthNames.
    • In Float class (an indirect subclass of Number. Pi. Evaluating Float Pi in the workspace, answers E.g. 3.14159
  • To hold changing values that should be the same for all instances of the class.
    • You create a class variable in the Frog class, in LB-22 p2 called FrogCount
      • Class methods created or modified:- frogCount, initCount, new, initialize
      • Instance methods accessing class variables created.
      • noOfSiblings, new

Scope

Can be used directly by the methods of the class, its subclasses, instances of the class or any of its subclasses.

Top of Page

 

Class -Instance Variables

  • These are rarely used. See M206 Ch. 22 page 6.
  • Begin with an upperCase letter.
  • Are used in the EIS class See chapter 27 page 12. Note the OU course M206 sometimes makes portions of this chapter optional.

 


Global Variables

Global variables are used to give easy access to commonly used objects. Such as

  • The names of classes e.g. Lefty
  • Colours that are referred to as Red, Green, Blue, Purple etc.
  • Do not confuse how Green and green are used.
    • Green is global variable, and used as an argument to the message colour: E.g.
      colour: Green
    • green is a method named in the protocol of Frog class. This method uses the global variable Green in its code.
    • Therefore green is a corresponding message that can be sent to instances of the Frog class. E.g.
      aFrog green
  • Global variables always start with an upperCase letter. E.g. Green.
  • The LearningWorks program provided on the M206 OU course does not provide an easy way of declaring global variables.

Top of Page

Scope

  • They can be assessed from anywhere.
  • They can be used in any method.
  • This does not respect encapsulation and therefore can be rather dangerous to use.
  • WARNING. Never attempt to assign anything to a global variable such as Red.

Top of Page


Exercises and Questions

Temporary variable

Examine the following 3 line expression series. Do not evaluate until after you attempt to answer questions 4a-c.
| myName |
 myName := 'John'.
Dialog warn: 'Hello', myName
Code Comments
| myName |
Declares a temporary variable called myName. A decimal point is NOT required after a temporary variable declaration.
After this line and before the next line the value of myName is nil
 myName := 'John'.
The assignment message := assigns the string literal 'John' to the variable myName.
Decimal point required.
Dialog warn: 
Displays a dialog box on the screen. See Tutorial 16. Dialog warn: Note: A Dialog warn: box answers with nil
 'Hello', myName
Code for the wording that appears in the dialog box. Note the concatenation of string literal 'Hello' and the value of temporary variable myName by using the comma ,
 Dialog warn: 'Hello', myName
Final line in expression therefore decimal point is optional

Top of Page

 


Question 1.
a. Write down the exact message that you expect will be displayed in the Dialog box

 

b. After clicking the button in the Dialog Box, what message answer should appear in the Workspace Display Pane?

 

c. Will the temporary variable myName appear in the Workspace Variables list pane.

 

Go to Answers 1a-c.

 


Exercise 1. Evaluate ALL of the following 3 line expression series, below in 1 go.
I.e. Highlight all 3 lines and click evaluate.
| myName |
 myName := 'John'.
Dialog warn: 'Hello', myName
Check that the answers to questions 1a-c are correct.

 

Question 1d. What button appeared on the dialog warn box?
Note: Dialog warn boxes always have this single button.
Go to answer 1d.

 


Question 1e. It is required that a space is inserted between Hello and John in the dialog box.
Suggest 3 ways of altering the following to achieve this space!
| myName |
 myName := 'John'.
Dialog warn: 'Hello', myName
Go to answer 1e.

Top of Page



Question 2.
What results do you expect if you just evaluate the single line:-
| myName |
Go to answer 2.

 

Exercise 2.
Evaluate and check result is as per answer 2
Question 3.
You have just declared myName as a temporary variable in exercise 2. State what you think will be the result of evaluating the single line
 myName := 'John'.
Go to answer 3.
Carry on straight away with Exercise 3

Top of Page


Local Variables

Exercise 3. Evaluate and check result is as per answer 3. Clicking the Create it button will declare myName as a local variables. This will place myName in the variable list pane.
Check that myName is in the Variable list pane. If this is not the case pay particular attention to answer 3, and carry out exercise 3 again.

 


myName is now a local variable, its scope is different from its previous use as a temporary variable. To demonstrate the difference in the scope you will carry out exercises similar to those in the previous temporary variable section.

Exercise 4. Evaluate
| myName |

You will be informed that myName is already defined (perhaps in an outerscope).
Click the cancel button.
This is informing you that the variable is already declared. Thus proving that the scope is much wider than that of the temporary variable. In fact you can close this LearningBook, save it, then re-open the same book, the local variable and its value still exists. The value is still nil until the next exercise.

 


Exercise 4.
Evaluate
myName := 'John'.
Dialog warn: 'Hello', myName
Works exactly as expected, setting the value of myName to 'John', and displaying the dialog box, and the Dialog warn: box answering with nil.

 

Question 4.
State 3 ways you can find out the current value of the variable myName.
Go to answer 4.

Top of Page


Exercise 5.
You are now required to place a space so that the Dialog box displays Hello John instead of HelloJohn.
If you have not tried the ways in answers 1-3, you may like to do that now. These are fairly straight forward, and if you fully understand the alterations made it is not necessary to carry them out.
In the before you try the final alternative way.
Because this is a tutorial on variables we will use an additional variable that will be named aSpace to provide a solution.

 

First you will remove the local variable myName.
  1. Click on myName in the Variable list, so that it is highlighted.
  2. Click on the Delete button underneath the list, note that myName is no longer in the list
Start with the original expression
| myName |
 myName := 'John'.
Dialog warn: 'Hello', myName
  1. Amend the first line so that an additional variable aSpace is declared
  2. Insert an additional line that assigns the string literal ' ' to the variable aSpace
  3. Amend the last line by concatenating the variable aSpace into this line. Take note off how this was done with the variable myName
Evaluate your solution, and correct it if required .

 

Go to Solution 2

 

Exercise 5.
Remove the declaration line, allow the 2 local variables to be created.

Top of Page

Instances of a class.

Local variables that reference instances of a class are created using expressions, as follows, and clicking on the create it button
aFrog :=Frog new  
myAccount :=Account new  
aString :=ByteString new: 5  
myArray :=Array new: 5  

Class Variables

There are very few examples of using class variables in the M206 OU course. You are likely going to be using class methods and possibly class variables in a TMA. This question appears to create problems for students.
As you do the course note how you use class methods.
  • Messages for class methods are sent to the class.
  • You have already used a class method and sent a message to a class in this tutorial. Have you spotted this fact. Clue classes, class variables and global variables start with an upperCase letter.
The message new has been sent to various classes.
The message warn: has been sent to the Dialog class.

 

In LB 22 you will create a class variable FrogCount.
  • Pay particular attention to how you
    • use this class method.
    • send messages to it.

Also in LB 22 you will work with the Date class. The date class has 5 class variables.
  • Pay particular attention to...
    • All the practicals
    • The discussion to the initialise method, LB-22 d9, which discusses ...
      • the class variables.
      • the use of the # character. (notation for a collection known as arrays)
    • How instance methods use class methods/variables. LB-22 p11

Top of Page


 

Answers to Questions


Answer 1a. The message will be:
HelloJohn
Note there are no single or double quotes, and also no space between Hello and John. You will shortly be asked to rectify this and insert a space.
Answer 1b. Nil will appear in the Workspace Display Pane
Answer 1c. Temporary variables do NOT appear in the Workspace Variables list pane.

 


Return to question 1a-c.
Answer 1d.
The box had an OK button.

 


Return to question 1d.

 



Answer 1e.
You could use any of the following alternatives. If you like you can try them.
  1. Simply type a space at the start of the string literal. I have typed in 2 spaces to make it easier to see.
     myName := '  John'.
  2. Simply type a space at the end of the string literal. I have typed in 2 spaces to make it easier to see.
    Dialog warn: 'Hello  ', myName
  3. Type after the comma ' ',
    • a single quote
    • a space I have typed in 2 spaces to make it easier to see.
    • a single quote
    • a comma
    Dialog warn: 'Hello' , '  ' , myName
  4. By using another variable that refers to string literal ' '
    • You will be using this method later in the tutorial, after you have had some practice with local variables.

Return to question 1e..

Top of Page


Answer 2.
Smalltalk realises that you have just declared a temporary variable, and that you have not used that temporary variable and warns you with a pop up window that states myName is never used with buttons Remove it, proceed, Cancel.
Click the proceed button which ensures that the line is evaluated and the temporary variable is declared.
When developing complicated methods you may wish to build the method up slowly, checking how the unfinished method is working at its current step in it's development. You could therefore get this message, its is OK to proceed if this is required.
Return to question 2.

 



Answer 3.
Smalltalk has already forgotten that you declared the temporary variable, because the scope for the temporary variable was in the expression series i.e. the single line | myName| in which it was declared.
In exercise 2. It does not recognise myName and therefore assumes it is an undeclared variable and a window pops up stating myName is undeclared with buttons Create it, correct it, Cancel.
Click on the Create it button.
Return to question 3.

 



 

Answer 4.
  1. Click on the name myName in the Variable list pane, then click on the inspect button.
  2. Evaluate myName in the Workspace.
  3. Evaluate myName inspectin the Workspace.

Return to question 4.

Top of Page


Solutions to Exercises


Solution 2.
| myName aSpace |
aSpace := ' '.
myName := 'John'.
Dialog warn: 'Hello', aSpace, myName
Notes:
  • Don't forget the period at the end of the line aSpace :=' '.
  • Dialog warn: 'Hello' , aSpace , myName
    The above is another way of writing the last line using white space on either side of the comma to make it stand out, and the line easier to read. This white space has nothing to do with the space that appears in the dialog box.
Return to exercise 2.

| Home | Previous Tutorial 4. Class Browser | Next Tutorial | Top of Page |

 

 

Ammendments
17 Jun 01, Clarify Global variables

Copyright © John McGuinn 2000 -01