Search code examples
javaconstructordeep-copy

How deep should copy constructors get


  1. Should defensive copies always be made for object references of mutable objects passed to constructors ?

  2. If yes, then how 'deep' should I go in making copies. In the following example should I make deep copies inside copy constructors of all classes involved ?

Eg:

class Graph {
    AdjacencyList;
    public Graph(Graph graph) {
      this.list = graph.list;   // shallow copy
      OR
      this.list = ArrayCopy(graph.list);  // deep copy
    }
}

class DFS implements GraphAlgo {
   Graph g
   DFS(Graph g) {
     this.g = g;   // shallow copy
     OR
     this.g = new Graph(graph)  // deep copy
   }

   DFS(Algo algo) {
     this.g = algo.g;  // shallow copy
     OR
     this.g = new Graph(algo.g);  // deep copy
   }

}

class Algo {
   GraphAlgo galgo

   Algo (GraphAlgo dfsalgo) {
      galgo  = dfsalgo  // shallow copy
      OR
      galgo = new DFSAlgo(dfsalgo); // deep copy
   }
}

3.. What if some class forgets to implement deep copy ? Does it mean I will never have a safe deep copied object ? Any way to prevent this ?


Solution

  • Should you be defensive?
    Only if you need to be.

    How deep should you go?
    As deep as you need to.

    Sound trite? Well, the basic answer to these type of questions is "do as little as you need to do to deliver the required functionality".