Navigation:  Tutorials > Beginners Guide to Smalltalk > Programming in Smalltalk > Creating the Question class >

Add the accessor methods

Previous pageReturn to chapter overviewNext page

First of all add the following methods to be able to get the values of the three instance variables.


       "Answer the branch in the knowledge tree to take as the result of a 'yes' answer

       to the receiver's question."




       "Answer the branch in the knowledge tree to take as the result of a 'no' answer

       to the receiver's question."




       "Answer the receiver's question as a text String"



It will certainly be useful to be able to access the values of these variables separately. However, once an instance of Question has been created we should never need to set the values of these variables again. Therefore, it makes sense that we should be able to use a private method to set all of these variables at once during instance creation. We'll use the following method to do this:

text: aString yes: yesPath no: noPath

       "Private - Set the text of the receiver to aString and the yes and no branches to

       yesPath and noPath respectively. This is a bit tricky. At the end of this operation

       we want the receiver to have completely swapped its identity with the original

       noPath. This is a bit of a kludge (since there are better ways to insert the receiver

       in the knowledge tree at the right point) but it is the simplest solution for this

       example program."


       text := aString.

       yes := yesPath.

       no := self.


       self become: noPath


Okay, so you've spotted the final line and want to know what that is all about. Well, to be honest, the use of the #become: message is beyond the real scope of this chapter and its use in this example program is only due to the fact that I wanted to shorten the program to make it easier to understand. However, for those who are interested, the tip below explains why it is here.

Tip: Imagine an existing knowledge tree for the game (I suggest you refer back to the original diagram) and we have got to the situation where the computer does not know the animal in question. Let us assume for the sake of this description that the computer believes you are probably thinking about an "eagle" but, in fact, you are thinking about a "sparrow". What we need to do is to create a new Animal object representing the "sparrow" and also to create a new Question that is capable of distinguishing the two animals. When we have completed linking these two new objects into our knowledge base the original Question that led to the "eagle" node will now have to point to the new distinguishing Question node. The easiest way to do this is to ask the two objects (the "eagle" and the new question) to swap identities. This is what #become: does.