Wednesday, February 27, 2013

Shallow Copy vs Deep Copy


Suppose you have a Department class to represent a Department at school and a Teacher class to represent a teacher. The Department class has properties such as Title, Block, and a collection names teacher. The Teacher class has properties such as FirstName and LastName.
Now suppose you build a Department object and assign it some Teachers.
A shallow copy of the Department would create a new Department with the same Title and Block. Its teacher’s property would point to the SAME collection as the original Department class. That means, for example, if you remove a teacher from the new Department's Teachers collection, that teacher is also removed from the original Department's collection because they are sharing the same collection. Similarly if you add or rearrange the Teachers collection for one of the Departments, the other sees the change, too.
In a deep copy, the new Department gets a NEW Teachers collection that it doesn't share with the old Department object. That means you can add or remove Teachers from the new Department object's collection without affecting the original Department object.
In fact, for a true deep copy the new Teachers collection is filled with copies of the Teacher objects in the original Department's collection, not references to the same Teacher objects. That means you can even change their FirstName and LastName properties without changing the values in the original Teacher objects.
This demonstrates some of the complexity and confusion of shallow versus deep copying. In this example, you probably want each Department to have its own Teachers collection so you can add and remove Teachers from them independently. But you may not want to have two Teacher objects representing the same person--you may want to have one unique Teacher object for each person.
If you define your own Clone or Copy method for the Department class, then you can decide exactly what kind of copying you want to do: shallow, deep, or something else where you might give the new object its own Teachers collection but fill it with references to the same Teacher objects.

No comments:

Post a Comment