Where to clone?

jrvbdeveloper

Member
Joined
Jul 15, 2007
Messages
17
Programming Experience
Beginner
Hi,

I was wondering what is best practice with regards to cloning objects, i.e. should the calling routine clone the object, or should it be cloned where it exists?

For example, if you are accessing a property, should the property be cloning the object or should you be cloning it?

Similarly, what if you are creating a new instance of a class, and passing it some objects. Should you clone the objects then pass them, or should the class be cloning the objects itself?

Thanks in advance!
 
A class can implement ICloneable interface, it has one member Clone method where the class creates a new instance and copy its internals needed to make an object copy and return this. The clone could be deep or shallow copy. This is the only place you have to think about cloning when writing a class. You implement it if you think there is a use for it.

The use of this method for classes that support it may be for easy copies of ready configured objects, it could also be for cases where you want to secure an "original" object from changes when you are passing it somewhere it could be changed. In special cases like imaging I've seen it has also been used where the original object holds a file lock and you clone it to copy the data in order to dispose and unlock the original, but I don't think this is a very legitimate use of cloning. So the only question you have to ask yourself as user of class objects that is cloneable is: "do I need a copy?". If so the documentation will tell if the objects clone copy is deep or shallow so you can make the decision if it's good enough for you or if you have to write code as workaround.
 
Thanks for your reply.

I guess I used incorrect wording, when I say clone I meant just any copy. So it could even be a collection or an array or anything else. If you need to create a copy, at what level should it be done?

Lets say an array is being passed to a class. Should the class create a copy of the array? Or should the calling routine copy the array and then pass it? Similarly with properties in a class, should the properties return a copy always?

Thanks in advance.
 
No, I don't see a need for copy/clone here.
 
Back
Top