[Newbies] Object references
Miguel Enrique Cobá Martínez
miguel.coba at gmail.com
Mon Apr 20 23:41:45 UTC 2009
Hi all,
I have a question regarding the correct use of object references. Maybe
this has already been asked before. If so, I will thank any pointer.
I have a ClassA that contains a collections of objects of ClassB
Object subclass: #ClassA
instanceVariableNames: 'list'
classVariableNames: ''
poolDictionaries: ''
category: 'Test'
ClassA >> list
^ list ifNil: [ list := OrderedCollection new ]
Object subclass: #ClassB
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'Test'
ClassA can add and remove objects of ClassB at any time.
When a ClassB object is removed from ClassA, the object is not needed
anymore so, as nobody else references it, the Garbage Collector dispose it.
That is ok, and the intended behavior.
Now, after a time, a new class named Group was created, to manage lists
of objects of classB, imagine a kind of bookmark.
Object subclass: #Group
instanceVariableNames: 'list'
classVariableNames: ''
poolDictionaries: ''
category: 'Test'
Group >> list
^ list ifNil: [ list := OrderedCollection new ]
This class needs to work the following way:
- I can add and remove objects of ClassB to a Group any time.
- When an object of ClassB is added to a Group, there are 2 references
to the object.
- When an object of ClassB is removed from Group, the reference to
ClassB object from Group is removed and now only ClassA has a reference
to the object.
But:
- If I remove the object from ClassA, the object must also be removed
from Group, because the Group can only reference objects of ClassB that
are actually part of a ClassA object.
I think that this behavior can be achieved the following way:
When deleting an object of ClassB from an object of ClassA, all the
Groups must be scanned to search for ocurrences of the object of ClassA
and remove it from Group and then remove it from ClassA
This has the following drawbacks:
- is not atomic, must remove from 2 places to succed
- is slow if there a lot of object in each group
- is, appears to me, not elegant.
I can also add a reference in each ClassA object to its ClassA parent
and a list of references to the groups the object is part of.
This is even trickier, because you now must update both the ClassA and
the ClassB each time you associate an object with another.
The question is. When you have an object that is referenced from many
places, but only one of them is the correct according to the problem
domain, how do you manage the adding, removing and updating of the
object to the other interested?
Is there a guideline here?
Thanks for the advise,
Miguel Cobá
More information about the Beginners
mailing list