My particular situation is related to Java, but I believe this is a more general OOP question than just Java programming.The Question: Should mutator methods perform deep or shallow copies?An example:Let's assume my object has the following structure:public class MyObj {  ArrayList<Integer> myList;  //constructors, etc.  public void setMyList(ArrayList<Integer> list) {    this.myList = list; //Option 1    //OR    this.myList = new ArrayList<Integer>(list); //Option 2  }}My assumption is that Option 2 is best.  This is because it prevents an external class from having direct access to MyObj's list.  For example, if I did:public class SomeOtherClass {  public static void main(String[] args) {    ArrayList<Integer> exampleList = new ArrayList<>(Arrays.asList(1, 2, 3));    MyObj a = new MyObj();    a.setMyList(exampleList);    exampleList.add(4);  }}At the end of main, Option 1 means that a.myList contains 4, while Option 2 means a.myList still consists of 1, 2, 3.  To me, the second seems preferable.Is there a standard/convention regarding this situation?
Should `setX(Object o)` methods perform deep or shallow copies of objects?
object oriented;programming practices
Either approach can be correct; it depends on the semantics you want. Basically, the difference is that the version with the copy means set myList to contain these elements: list, whereas the version without the copy means set myList to be this list object: list. I think the former semantics are more often desirable (especially since lists are fairly transparent: we usually think of lists solely in terms of the elements they contain, and not in terms of some stable identity independent of the contents); but there are valid uses for the latter.If you go with the copy approach, by the way, here are a few things to keep in mind:It's a good idea to make sure your get method returns an unmodifiable list, using either Collections.unmodifiableList or something like Guava's ImmutableList.copyOf. (Note that you probably do not want to just return new ArrayList<Integer>(myList), because although that protects myList from being modified by client code, it does not make it obvious that modifying the returned list does not affect the original object. It's better for myObj.getMyList().add(3) to fail noisily.)List may not be the appropriate abstraction if you don't actually want client code to manipulate the list as a list. And even if your getter returns List<Integer>, it might be appropriate for your setter to accept Iterable<Integer>.