Suppose you have to implement Graph class, containing some algorithms, using dfs (depth-first search). For instance, it might be connectivity check and Graph class would look like that:
class Graph {
void dfsConnected(int v) {
visited[v] = true;
//indexing over v's adjacencies and calling dfsConnected recursively
}
bool isConnected {
//indexing over vertice list and calling dfsConnected
}
}
Suppose we have a bunch of algorithms, using dfs in this class (every of them uses specific dfs).
The problem is visited array:
- we could define it as a private field for every dfs like
visitedConnectivity,visitedTopSorting,visitedBridges, etc. So we will have a lot of private variables in the every instance ofGraph. And what if we have 3-4 such “global” variables for every dfs? - we could pass
visitedas adfs‘s argument . In this case, we will have overhead on the every dfs call.
So, what is the easiest and real-world used solution for this problem? Of course, it is related not only to graph algorithms, but I found it easier to explain it in dfs terms.
The more OOP way, in my opinion, is delcaring a field
visitedfor each DFS class, and make it run its own DFS….It will prevent you from keeping track ‘what did I allocated? where is it connected to? etc…”
Your DFS will be much more capsulated, and will require fewer data, then adding an extra parameter for each dfs, which you will have to maintain separately.
The performance issue in here is neglected [in most cases] to the readability and maintainability you achieve with encapsulating as much data as possible in the class itself.