假設我們有一個只有1個函數的類,例如:compute DFS。 以下哪項是首選方法,爲什麼?構造函數的最佳實踐
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();
結果將如何傳遞給調用者?遍歷是否有副作用? – Thilo