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

Creating a class variable to hold the knowledge base

Previous pageReturn to chapter overviewNext page

Sometime ago we mentioned that we would need to hold the root of the knowledge base in a variable, if only so the game will know where to get hold of it when it starts. Now is the time to create and initialize this variable. We could, of course, choose to use a global variable for this purpose. However, it is usual to frown upon global variables since they may clash with similarly named variables in another application. Fortunately there is an excellent alternative; to use a class variable.

We have seen how instance variables can be used to hold data that is associated with a particular instance. Well it is also possible to create another type of variable that is associated with a particular class object. It's very easy to add class variable slots to your class by using the Class Browser. Let us choose to add a class variable called KnowledgeBase to the Animal class. First of all select Animal in the browser and then choose the Class definition mode to display the existing definition. Modify this as shown below and accept the change using Ctrl+S.

Object subclass: #Animal

       instanceVariableNames: 'name'

       classVariableNames: 'KnowledgeBase'

       poolDictionaries: ''

       classInstanceVariableNames: ''

 

Tip: It is conventional for the names of class variables to begin with an uppercase letter.

This new variable can be used like any other but only within the scope of the Animal class. This means that you can use it in any methods (either instance or class) that are defined for Animal or its subclasses. You will not, however, be able to successfully reference the KnowledgeBase variable from any other class or workspace. This means that you would not be able to reference it from within the Question class, for example. The good thing about this additional level of privacy compared with true globals means that no other class or program can modify this variable inadvertently.

Tip: Sometimes you might want to allow methods outside the normal scope to be able to access a class variable. This is quite possible, and is simply a matter of defining some accessor methods in much the same way as you would for instance variables. The only difference, of course, is that the accessor methods you define for a class variable must be defined as class methods rather than instance ones. Anyway, in our Animal game will only need to reference the KnowledgeBase from within the Animal class so we'll have no need for any accessor methods.