Navigation:  Tutorials > Beginners Guide to Smalltalk > Programming in Smalltalk > Adding methods >

Adding accessor methods

Previous pageReturn to chapter overviewNext page

One of the things about object-oriented programming in general, and Smalltalk in particular, is that it is not possible to gain access to the data stored in an object except by means of methods written in the class. For example, we will want to be able to set and retrieve the value in the name instance variable slot of an Animal and, to do this, we will need to write a couple of methods. These are known as accessor methods. We will want to add methods for #name and #name:.

Select the Animal class in the Class Browser and choose the Method/New command. This sets up the browser ready to receive a new method definition in the Method Source pane. Enter the following method:


       "Answer the name of the receiver"        



Choose Workspace/Accept or type Ctrl+S to accept this new method definition into the image. You'll see that, after the browser compiles the method, it is then redisplayed in the source pane in coloured text. The different colours identify different parts of the language and quite soon you'll find this makes the methods easier to read.

The method that we have just added included the ^ symbol to indicate that a value should be returned from the method. The intention of this particular accessor method is just to return the value held in the name instance variable. Now let us add another method to set the value of this variable. Once again choose Method/New and enter and accept the following code:

name: aStringName

       "Private - Initialize the name of the receiver to aStringName"        

       name := aStringName


This method receives one parameter that I've given a name of aStringName to identify it. Notice how the name chosen for this parameter can indicate to the reader of the code what type of object is acceptable here, e.g. a String. This is purely done for readability, so at no time will the system insist that actually only a String is allowable. It can be a useful practice to get into the habit of naming parameters in this way so that someone browsing through the methods of your program in future will have a better idea how to use them.

The sole purpose of this method is to assign the contents of the passed parameter to the name instance variable. Notice that I have chosen to label the method as Private within the method comment. It was discussed in the previous chapter that Smalltalk does not enforce such method privacy but, once again, this is useful documentation for any programmer intending to make use of our Animal class. What it indicates is that, under normal circumstances, one would not expect to call this method directly.

Tip: You may be wondering what this method is for if it is not intended to be directly called. We'll see the reasoning for this later.