Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 816
JavaDeveloper Avatar asked Aug 05 '13 02:08

JavaDeveloper


People also ask

What are the rules for a constructor?

The two rules for creating a constructor are: The name of the constructor should be the same as the class. A Java constructor must not have a return type. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.


2 Answers

Constructors are meant to initialize the data fields in the object. Given the choices, the second approach seems more correct.

Although what might be better is to include the doDFS method in your graph object. It's usually bad practice to create an entire class for a single simple function. The doDFS method is specific to the graphs it works with, so including it in whatever graph class you have is natural.

like image 165
Steven Avatar answered Oct 18 '22 06:10

Steven


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.

like image 38
Commander Worf Avatar answered Oct 18 '22 06:10

Commander Worf