javasoftware-design

Constructor best practices


Lets say we have a class with only 1 function, eg: compute DFS. Which of the following is preferred approach and why ?

Approach 1:

public class DFS {

    public DFS(Graph g) {
      dfs(g);  // <--- computation invoked from constructor.
    }

    private void DFS(Graph g) {
       // do dfs traversal
    }
}

Client:
DFS dfs = new DFS(graph);


Approach 2:
public class DFS {
    Graph g;
    public DFS(Graph g) {
       this.g = g
    }

    private void doDFS() {
       // do dfs traversal
    }
}

Client:
DFS dfs = new DFS(graph);
dfs.doDFS();

Solution

  • The latter. The convention is that the constructor creates a blank object that is ready to do work, not an object that immediately begins to work.

    Although both will function, the former is unclear.