Should `setX(Object o)` methods perform deep or shallow copies of objects?

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?

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>.

Note that the same question arises for getters. Not copying a mutable field in a getter means exposing the content for modification.


You’re speaking about shallow vs deep copy, but you snippet show no vs shallow copy. A deep copy would go like

void setTwoLevelList(List<List<Integer>> twoLevelList) {
    this.twoLevelList = Lists.newArrayList();
    for (List l : twoLevelList) this.twoLevelList.add(Lists.newArrayList(l));
}

or even more complicated for deeper structures or infeasible for something like

void setListOfT(List<T> t) {
    ??? how to copy T?
}

The problem in Java is that it has neither a shallow nor a deep copy. It has clone, which is broken by design and underspecified:

Creates and returns a copy of this object. The precise meaning of “copy” may depend on the class of the object.

Back to the question

So should we do no, shallow, or deep copy in setters?

Ideally, there should be no setters at all. Immutable objects are the easiest to use, but unfortunately, not always possible.

There’s no general rule for setters, except that you should avoid them (even more than mutable state in general). Often, an immutable object with a builder or a wither is an alternative.

If you have to write a setter, then I’d recommend to make the field immutable, e.g., use an ImmutableList. If its members are immutable too, then there’s no reason to copy anything.

Otherwise, I would copy as deep as I can. Sometimes, an exception must be made for performance reasons, e.g., when passing large objects frequently. In a such a case it’s advisable to make the method package private

A good solution is often something like

void setMyList(List<Integer> list) {
    this.list = ImmutableList.copyOf(list);
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật