Newbie Question: How to manage instances?

Jarvis, Robert P. Jarvisb at timken.com
Tue May 25 12:17:25 UTC 1999


>From: Tim Cuthbertson [SMTP:timcuth at bellsouth.net]
>If I create an instance, e.g.,
>    aTrack := Track new
>and then create another instance, again using
>    aTrack := Track new
>is there any way to get to the first instance, again?

No.  Once you no longer have a reference to an instance you can't get it
back.  What you need to do is ensure you've always got a valid reference,
something like

	tracks := OrderedCollection new.
	aTrack := Track new.
	tracks add: track.

This requirement to maintain references to instances is no different than in
other languages.  Consider the following example in C++:

	Track *pTrack;

	pTrack := new Track;
	pTrack := new Track;

The code above 'loses' the memory allocated by the first 'new'.  In the case
of the C++ code the memory is permanently lost with no hope of being
reclaimed, until the process making the allocation terminates.  In the
equivalent Smalltalk case, given in your initial message and quoted above,
the 'lost' instance will be garbage collected automatically and the memory
will eventually be available for reuse with no further action required on
the part of the developer.

>Suppose I created eleven instances of Track and then wanted to add them to
an instance of Album, a subclass of Set. Even if I used >eleven different
temp variables to hold references to each Track, I am now faced with a
similar problem for my instances of Album. If I >don't retain the temp
variable I used when I created it, I don't understand how to find it, again.

You need to add your tracks to something which will maintain a reference to
them, then maintain a reference to whatever it is that holds your tracks.
Quite commonly your data model will be referenced by your user interface,
which is referenced by the Smalltalk system, and thus things hang together.
When I'm developing code I usually (but not always :-) write the data model
first, exercising it from a workspace.  Eventually I get tired of using the
workspace to test the model and begin writing the user interface.  This
works well for me. I hope this helps.

Bob Jarvis
The Timken Company





More information about the Squeak-dev mailing list