On May 03, 2006, at 15:00 UTC, Jason Essington wrote:

> For a problem like this, I'd be inclined to define an interface  
> Cloneable with one method clone() which when implented would return a  
> new object that was a deep copy of the instance it was called on.

That's a good idea; I've done this in the past and it's worked out nicely.

To make it slightly more general, add a parameter to the clone() method, 
"deepCopy as Boolean", which determines whether object references inside the 
object should be simply copied as references, or cloned themselves.  (In the 
latter case, of course, you still have to decide whether to deep-copy those as 
well -- but usually that's what you'd want.)

There is a gotcha to watch out for with this approach, however, and that is 
with circular references.  If anywhere in your data structure, you have a 
reference chain that links back up to itself, and you try to deep-copy this, 
you could end up in an infinite loop of cloning.  Soon you'd be neck-deep in 
clones, like when Homer bought that evil (but comfortable) hammock, and the app 
would crash.

To avoid this, you'd need to pass around a dictionary that maps original 
objects to their clones.  Then, any time you're about to create a new clone, 
you first look in this dictionary to see if it's already been cloned, and if so 
use that.  If not, create the new clone and stuff it in the dictionary.

Of course, often we avoid circular references anyway; if you can be sure this 
won't come up, then you can avoid this extra complexity.

> You could have any object you plan on storing in the array implement  
> Cloneable, then you could have a module method ArrayCopy(origArray,  
> newArray) which clones every object in the old array and adds it to  
> the new array.

Well, you can't make this method general, since it needs to match the specific 
type of the array it's going to operate on.  The reasons for this take a little 
thought to see, but they are quite legitimate.

> Come to think of it, This functionality is needed often enough that  
> I'm surprised that it isn't included in RB.

Well, RB itself could make such a general method, by bending the rules -- but I 
think they generally don't like such rule-bending.  And without that, such a 
method is not possible.

Best,
- Joe

--
Joe Strout -- [EMAIL PROTECTED]
Available for custom REALbasic programming or instruction.

_______________________________________________
Unsubscribe or switch delivery mode:
<http://www.realsoftware.com/support/listmanager/>

Search the archives of this list here:
<http://support.realsoftware.com/listarchives/lists.html>

Reply via email to