I have a code which takes a bipartite graph as an input and returns a map with key"1" with value which is a list of "nodes in set1" and key"2" whose value is list of "nodes in set2". Now, map is mutable. In theory I should use a defensive copy for returning a map. But, in this case is it really required ? It appears an overkill.
ex:
class BiPartite {
Graph graph;
Map bipartite
Bipartite(graph) {
this.graph = graph;
}
void calcBipartite() {
// calculate map
}
Map getMap() {
// should i make defensive copy ? Appears overkill.
}
}
Note how the constructor Point(Point p) takes a Point and makes a copy of it - that's a copy constructor . This is a defensive copy because the original Point is protected from change by taking a copy of it.
Java Practices->Defensive copying. A mutable object is simply an object which can change its state after construction. For example, StringBuilder and Date are mutable objects, while String and Integer are immutable objects. A class may have a mutable object as a field.
It depends :)
Collections.unmodifiableMap(map)
in getMap()
and document that it reflects the mutable state of the BiPartite object. That can be a valid approach as long as the BiPartite object is not supposed to be threadsafe. If the client wants to keep the returned Map as a stable snaphot, she can copy it herself. If that's not needed, she can benefit from the fast wrapping operation.Basically it boils down to: Think about how the BiPartite class and its methods should be used, pick a suitable implementation for that and clearly document both the behavior of the class and the reasoning behind it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With