Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice: Adding child node to a parent in child constructor or not?

Tags:

oop

I'm working with some code that adds a child node to it's parent in the child's constructor. The code looks something like this:

Class:

class Node1 {
  public Node1(Node1 parent, String name) {
     if(parent != null) {
       parent.add(this);
     }
     this.parent = parent;
  }

  private void add(Node1 child) {
    children.add(child);
  }
}

Usage:

Node1 parent = new Node1(null, "parent");
Node1 child1 = new Node1(parent, "child1");
Node1 child2 = new Node1(parent, "child2");

By implementing it this way the user of the Class Node1 doesn't have to explicitly add the child node (less code) to it's parent and you have guaranteed a child node has a parent.

I personally wouldn't have written it like this, but more like the following:

class Node2 {
  public Node2(String name) {
  }

  public void add(Node2 child) {
    children.add(child);
    child.setParent(this);
  }
}

Node2 parent = new Node2("parent");
Node2 child1 = new Node2("child1");
parent.add(child1);
Node2 child2 = new Node2("child2");
parent.add(child2);

So my question is, is this a good idea to implement it as shown in Class Node1 or are there any objections to do it that way? Or is there no argument of why one is better than the other?

like image 680
Hilbrand Bouwkamp Avatar asked Mar 10 '09 12:03

Hilbrand Bouwkamp


2 Answers

I personally don't like the first example because you are adding a Node which is not "ready" yet (as the constructor didn't finish executing). In most cases it will work fine, but in extreme cases you can have bugs that are quite hard to find.

like image 90
Grzenio Avatar answered Sep 21 '22 02:09

Grzenio


I would use second case as then I will be able to add children later but not only in the constructor.

like image 35
Mykola Golubyev Avatar answered Sep 22 '22 02:09

Mykola Golubyev