Should defensive copies always be made for object references of mutable objects passed to constructors ?
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 ?