The Graph Theory in C# (Part 3)

Focusing on the basic definition of the graph guided my quest to a good path. G = (V, E) means that, a graph is a collection of vertices and edges. As we all can see now, there are three objects involved here: the graph G itself, the vertices V and the edges E. But what are vertices? And what are edges? In the same way that I wanted my graph to be true to the definition, I needed my vertices and edges to implement the "official" definitions as well.

Let's break that down a little. The definition mentions "vertices" and "edges". These words are in plural form. Their singular forms would be vertex and edge, respectively. So that means "vertices" is a list of vertex instances/objects. Likewise, "edges" is a list of edge instances/objects. That's easy enough to express in C#:

public class Graph
{
    public List<Vertex> Vertices { get; set; }
    public List<Edge> Edges { get; set; }
}

This code defines a class Graph with properties Vertices and Edges, where Vertices is a list of Vertex objects and Edges is a list of Edge objects. As you can see, the definition G = (V, E) when expressed in C# is pretty straightforward. This won't compile, of course. Although C# knows what a List is, C# doesn't know what Vertex and Edge are. I need to define them as new classes.

The Graph looks simple. Too simple. Comparing this code to how my graph library now defines a Graph, my current version is nowhere close to this anymore! Yes, I started with this code, but it evolved in to something that gives the Graph a bit of smartness to help keep, protect and retain some level of data integrity.

Now this is important to understand. Even if I tried my best to be true to the definitions, I also need to try my best that the classes I create can be trusted. Although there may be nothing in the definitions that the graph needs to be smart with rules and what not, I should at least provide some means to help my library users use my graph objects properly.

However, the goal is the same. The features I add outside the definitions are still about data, because that's what my graph library is about: graph is just data. The guiding principle is that each of these objects should only be aware of itself. I would not, for example, create a Vertex that knows about another Vertex because that overlaps with the purpose of the Edge. The Vertex should only know about itself and how it can communicate itself to everyone else. Likewise, I would not create an Edge that knows about another Edge. The Edge should know only about itself and how it can communicate itself to everyone else.

My quest led me to evolve my Graph in to something a little more, a little different, but delivers pretty much the same intent. For now, let's keep it simple, shall we?

Comments