Newsgroups: comp.lang.smalltalk
Path: cantaloupe.srv.cs.cmu.edu!rochester!udel!gatech!bloom-beacon.mit.edu!news.tamu.edu!news.utdallas.edu!corpgate!bcarh189.bnr.ca!nott!cunews!dbuck
From: dbuck@superior.carleton.ca (Dave Buck)
Subject: Re: Newbie question - class method
X-Nntp-Posting-Host: superior.carleton.ca
Message-ID: <D7KGFr.91z@cunews.carleton.ca>
Sender: news@cunews.carleton.ca (News Administrator)
Organization: Carleton University, Ottawa, Canada
References: <3nh5lv$nt8@ixnews1.ix.netcom.com>
Date: Tue, 25 Apr 1995 01:07:03 GMT
Lines: 61

In article <3nh5lv$nt8@ixnews1.ix.netcom.com>,
Larry Marshall <lmarshal@ix.netcom.com> wrote:
>How or under what circumstances do you invoke a class method? I want
>to create one which initializes a class variable (Dictionary) and then
>places information in that dictionary. 
>
>Of course I only want to do this once (before any instances are
>created) so that all instances can reference values in the dictionary
>class variable.
>

A class method is simply a method that belongs to the class object
instead of to the instances of the class.  Class methods are typically
called by giving the name of the class followed by the method name.

Eg.
   WriteStream on: String new

The on: method is sent to th WriteStream class, therefore it must be a
class method.

There are two common ways to do what you want.  The first way is to
have an initialize method for the class.  The initialize method simply
sets up the class variable.  It's called manually from a workspace.
When you save the image after running this method, the initialized
value is saved in the image and will be there forever more until you
manually remove it.

Eg.
MyClass>>initialize
   MyStuff := Dictionary new.

The second way is called lazy initialization.  You write a class
method to check to see if your variable is nil.  If so, you initialize
it, otherwise, you return the existing value.

Eg.

MyClass>>myStuff
    MyStuff isNil ifTrue: [MyStuff := Dictionary new].
    ^MyStuff

With this technique, you never directly access the class variable -
you always call the class method to get the value.

SomeSubClass>>someMethod
    ...
    self class myStuff at: #hi put: 'Something'.
    ...

This guarantees that the class variable is always initialized before
it's used.

David Buck
dbuck@ccs.carleton.ca

_________________________________
| David K. Buck                 |
| dbuck@ccs.carleton.ca         |
| The Object People             |
|_______________________________|
