Newbie Question - Instance Variables

Boris Gaertner Boris.Gaertner at gmx.net
Thu Feb 5 13:06:39 UTC 2004


From: Ed Grant
To: The general-purpose Squeak developers list
Sent: Thursday, February 05, 2004 12:09 PM
Subject: Newbie Question - Instance Variables


I need some help.
What happens in this scenario?

    1. I create a new class (with few instance variables & methods).

    2. I creating several instances.

    3. I decide I need to add another instance variable to the new class.

Question: Can I add the new instance variable to the new class without
causing any problems?

Yes, this is possible.

If I can, will that new instance variable be duplicated in all the instances
that were previously created?

Yes, all exisiting instance of the class and all exisiting instances
of all subclasses are modified to reflect the new layout.

What will each modified instance object contain in the new instance
variable.

A nil.

If I can't, what process must I follow to add a new instance variable to
a class which has already be created and instanstiated?

As you can simply add (or remove) instance variables, an answer
to this question is not required.

Two tips are perhaps useful:
A. Imagine that you add an instance variable isOK that
and imagine that you want this variable to keep a boolean value.
2. In a new instance method, you check that value and you
do this as simple as possible:

  myMethod
    ^isOK
        ifTrue: ["do this"]
        ifFalse: ["do that"]

3. You create a new instance which is of course properly
initialized (you care for that), test you method and
everything looks fine.
4. You send  #myMethod to an old instance that was
adapted to the new class structure. You will get
an error notification with:
UndefinedObject does not understand: #ifTrue:ifFalse:
That is because your old instances have a nil in isOK
5. To enable old instances to use  myMethod, you can
write something like that:

 myMethod
   ^isOK = true
       ifTrue: []
       ifFalse: [].

This looks very strange, but we can find such code
in our image. (It was perhaps written exactly to
avoid problems with reshaped instances)

B.  In
ClassDecription>>updateInstances:from:isMeta:
(one of the methods that do the magic)
we find a comment that says:
"If there are any contexts having an old instance as receiver
it might crash the system because the layout has changed,
and the method only knows about the old layout."

This is a warning that there are some limitations.


Greetings, Boris



Ed Grant





More information about the Squeak-dev mailing list