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?