<p>I want to implement in Java a class for handling graph data structures. I have a Node class and an Edge class. The Graph class maintains two list: a list of nodes and a list of edges. Each node must have an unique name. How do I guard against a situation like this:
</p>

<pre><code>Graph g = new Graph();

Node n1 = new Node("#1");
Node n2 = new Node("#2");

Edge e1 = new Edge("e#1", "#1", "#2");

// Each node is added like a reference
g.addNode(n1);
g.addNode(n2);
g.addEdge(e1);

// This will break the internal integrity of the graph
n1.setName("#3");   
g.getNode("#2").setName("#4"); 
</code></pre>

<p></p>

<p>I believe I should clone the nodes and the edges when adding them to the graph and return a NodeEnvelope class that will maintain the graph structural integrity. Is this the right way of doing this or the design is broken from the beginning ?</p>

[{'answer_id': 63795, 'author': 'jjnguy', 'author_id': 2598, 'author_profile': 'https://Stackoverflow.com/users/2598', 'pm_score': 1, 'selected': False, 'text': '<p>In my opinion you should never clone the element unless you explicitly state that your data structure does that.</p>\n\n<p>The desired functionality of most things needs the actual object to be passed into the data structure by-reference.</p>\n\n<p>If you want to make the <code>Node</code> class safer, make it an inner class of the graph.</p>\n'}, {'answer_id': 63846, 'author': 'Jim Kiley', 'author_id': 7178, 'author_profile': 'https://Stackoverflow.com/users/7178', 'pm_score': 2, 'selected': False, 'text': "<p>It isn't clear to me why you are adding the additional indirection of the String names for the nodes.  Wouldn't it make more sense for your Edge constructor's signature to be something like <code>public Edge(String, Node, Node)</code> instead of <code>public Edge (String, String, String)</code>?</p>\n\n<p>I don't know where clone would help you here.</p>\n\n<p>ETA: If the danger comes from having the node name changed after the node is created, throw an <code>IllegalOperationException</code> if the client tries to call setName() on a node with an existing name.</p>\n"}, {'answer_id': 64598, 'author': 'davetron5000', 'author_id': 3029, 'author_profile': 'https://Stackoverflow.com/users/3029', 'pm_score': 0, 'selected': False, 'text': '<p>In addition to the comments by @jhkiley.blogspot.com, you can create a factory for Edges and Nodes that refuses to create objects with a name that was already used.</p>\n'}, {'answer_id': 64847, 'author': 'Rob Dickerson', 'author_id': 7530, 'author_profile': 'https://Stackoverflow.com/users/7530', 'pm_score': 3, 'selected': True, 'text': '<p>I work with graph structures in Java a lot, and my advice would be to make any data member of the Node and Edge class that the Graph depends on for maintaining its structure final, with no setters. In fact, if you can, I would make Node and Edge completely immutable, which has <a href="http://www.javapractices.com/topic/TopicAction.do?Id=29" rel="nofollow noreferrer">many benefits</a>.</p>\n\n<p>So, for example:</p>\n\n<pre><code>public final class Node {\n\n    private final String name;\n\n    public Node(String name) {\n           this.name = name;\n    }\n\n    public String getName() { return name; }\n    // note: no setter for name\n}\n</code></pre>\n\n<p>You would then do your uniqueness check in the Graph object:</p>\n\n<pre><code>public class Graph {\n    Set&lt;Node&gt; nodes = new HashSet&lt;Node&gt;();\n    public void addNode(Node n) {\n        // note: this assumes you\'ve properly overridden \n        // equals and hashCode in Node to make Nodes with the \n        // same name .equal() and hash to the same value.\n        if(nodes.contains(n)) {\n            throw new IllegalArgumentException("Already in graph: " + node);\n        }\n        nodes.add(n);\n    }\n}\n</code></pre>\n\n<p>If you need to modify a name of a node, remove the old node and add a new one. This might sound like extra work, but it saves a lot of effort keeping everything straight.</p>\n\n<p>Really, though, creating your own Graph structure from the ground up is probably unnecessary -- this issue is only the first of many you are likely to run into if you build your own.</p>\n\n<p>I would recommend finding a good open source Java graph library, and using that instead. Depending on what you are doing, there are a few options out there. I have used <a href="http://jung.sourceforge.net/" rel="nofollow noreferrer">JUNG</a> in the past, and would recommend it as a good starting point.</p>\n'}, {'answer_id': 65104, 'author': 'chrisk', 'author_id': 8814, 'author_profile': 'https://Stackoverflow.com/users/8814', 'pm_score': 1, 'selected': False, 'text': "<p>Using NodeEnvelopes or edge/node Factories sounds like overdesign to me.</p>\n\n<p>Do you really want to expose a setName() method on Node at all?  There's nothing in your example to suggest that you need that.  If you make both your Node and Edge classes immutable, most of the integrity-violation scenarios you're envisioning become impossible.  (If you need them to be mutable but only until they're added to a Graph, you could enforce this by having an isInGraph flag on your Node/Edge classes that is set to true by Graph.Add{Node, Edge}, and have your mutators throw an exception if called after this flag is set.)</p>\n\n<p>I agree with jhkiley that passing Node objects to the Edge constructor (instead of Strings) sounds like a good idea.</p>\n\n<p>If you want a more intrusive approach, you could have a pointer from the Node class back to the Graph it resides in, and update the Graph if any critical properties (e.g., the name) of the Node ever change.  But I wouldn't do that unless you're sure you need to be able to change the names of existing Nodes while preserving Edge relationships, which seems unlikely.</p>\n"}, {'answer_id': 354535, 'author': 'Julien Chastang', 'author_id': 32174, 'author_profile': 'https://Stackoverflow.com/users/32174', 'pm_score': 1, 'selected': False, 'text': '<p>Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "<a href="http://java.sun.com/docs/books/effective/" rel="nofollow noreferrer">Effective Java</a>" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.</p>\n'}]
['https://Stackoverflow.com/questions/63748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3885/']