Deepclone

You will often have user scenarios that require you to copy an existing object structure, such as handling revisions of things. The user may want a new revision, but requests you to start with the old object structure and tweak a few values.

In cases like these, it would be neat to use a cloning mechanism for your modeled objects. Once you have a cloning mechanism, you will soon discover that cloning one object will not suffice. You want to follow associations and clone owned child objects – but only in some cases; in other cases, you don’t want to clone the child objects, but rather reference the same ones from the clone.

Given this model:

2024-12-03 05h27 05.png

Let a ViewModel act as a definition for what the clone should do - like this, for example:

Deep Clone Example.png

Then, in OCL, do:

self.deepclone('Person_DeepClone')

where 'Person_DeepClone' is the name of the ViewModel being used as a definition for the creation of the new Person object.

The deep clone operator returns the new Person object, complete with a copy of the Home object and a link to OwnedBuildings of the current Person object.

A new copy of the Home object is created and linked to the new Person object because the ResidentialBuilding Nested ViewModel attached to the Home column defines details on how to created the object or objects. Then, a reference to OwnedBuildings association link is attached to the new created copy of Person because the column OwnedBuildings is not attached to a Nested ViewModel to define details on how to create OwnedBuilding objects - so only a reference to current link is attached. Since the current OwnedBuildings attached to Person can only be linked to one Person object and we are not creating objects but attaching a reference, this means that OwnedBuildings on current Person will nolonger exist on current Person object. Current OwnedBuildings objects will only be linked to and available on the new created copy of Person.

A good place to use this operator is in a method on a class. For example, CreateClone() : Person. That way, you just call self.CreateClone from a class action using the returned object as the root of the ViewModel the action opens.

In Conclusion, when using Deepclone to create copies of objects, for association links, consider whether to create new objects or retain references while regarding relationship cardinalities as they determine if objects in association links are moved to new Deepclone copy entirely.

See also the transform operator which is a DeepClone that can change type.

This page was edited 16 days ago on 12/05/2024. What links here