HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Simple Oriented Graph implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simplegraphjavaorientedimplementation

Problem

I wanted to implement a simple oriented graph as part of an exercise in both Object Oriented Programming and Data Structures. I wanted to make it as class-focused as possible, so I don't know if my implementation follows the standard adjacency list/matrix implementations.

I started reading on software design patterns, but I am still very new to them. Any suggestions to make this code leverage the applicable design pattern(s) is appreciated. Other than that, I'd like feedback on:

  • Style & readability



  • Maintainability & scalability



  • Efficiency



  • API Design



Graph.java

public interface Graph {
    boolean contains(T item);
    void addVertex(T vertex);
    boolean areAdjacent(T a, T b) throws Exception;
    void removeVertex(T vertex) throws Exception;
    void addEdge(T from, T to, int weight) throws Exception;
    void removeEdge(T from, T to) throws Exception;
    Collection getNeighborsFor(T vertex) throws Exception;
    void depthSearch(T start) throws Exception;
    void breathSearch(T start) throws Exception;
}


OrientedGraph.java

```
public class OrientedGraph implements Graph {
private HashMap> graph;

public OrientedGraph() {
graph = new HashMap<>();
}

public boolean contains(T vertex) {
return graph.containsKey(vertex);
}

public boolean areAdjacent(T src, T dest) throws NoSuchVertexException {
Vertex srcVertex = graph.get(src);
Vertex destVertex = graph.get(dest);

if (srcVertex == null || destVertex == null)
throw new NoSuchVertexException();

return srcVertex.hasNeighbor(destVertex);
}

public void addVertex(T vertex) {
Vertex vertexNode = new Vertex<>(vertex);
graph.put(vertex, vertexNode);
}

public void removeVertex(T vertex) throws NoSuchVertexException {
Vertex vertexNode = graph.get(vertex);

if (vertexNode == null)
throw new NoSuchVertexException();

Iterator> iterator = graph.va

Solution

Make constructor private in order to remove object creation code. Replace with public or protected method which calls private constructor and returns a new instance; i.e., a factory pattern. Suppose one has numerous arguments required for construction. This could be implemented using the Builder design rather than an awful, lengthy parameter list in your constructor. Or what if one maintained a collection of object instances in the graph object, controlling how many instances are ever created; i.e., an object cache. Or one might want to provide an easy way to copy an existing object's data, providing a copy constructor method.

Context

StackExchange Code Review Q#114313, answer score: 2

Revisions (0)

No revisions yet.