Here's the situation: I am trying to determine the where part of cloning an object to avoid modifying the original.
I have two options:
- Clone the object in the caller and pass the cloned object to a method ("callee"), thus preventing potential modification by the callee.
- Clone the object in the callee because the callee modifies the object it is passed, this making the assumption that the caller never wants the argument object to be modified.
I found this 6-year-old answer with a variety of opinions. Unfortunately it doesn't seem there was a real consensus.
Passing copy of object to method -- who does the copying?
Here's my question in code-form:
- Do I clone the object in the caller and pass the cloned object to the method?
public static void Main()
{
var foo = new Foo();
Bar.Baz(foo.DeepClone());
}
public static class Bar
{
public static void Baz(Foo foo)
{
/* ... modifies members in foo ... */
}
}
public class Foo { /* ... */ }
- Do I clone the object in the callee?
public static void Main()
{
var foo = new Foo();
Bar.Baz(foo);
}
public static class Bar
{
public static void Baz(Foo foo)
{
foo = foo.DeepClone();
/* ... modifies members in foo ... */
}
}
public class Foo { /* ... */ }
So, my questions are:
What are some good rules of thumb for where to clone objects across languages, but especially in C# and .NET-land?
Regardless of the answer(s), what are some good ways to document the behavior of methods that modify arguments, or methods that clone objects?