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:
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');
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 ?
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 many benefits.
So, for example:
You would then do your uniqueness check in the Graph object:
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.
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.
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 JUNG in the past, and would recommend it as a good starting point.