I am working with some code that adds a child of a node to its parent in a child constructor. The code looks something like this:
Grade:
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); } }
Using:
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 Node1 class Node1 not explicitly add the node's child (less code) to his parent, and you have guaranteed that the node's child has a parent.
I personally would not write it like this, but it looks 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 it good to implement it, as shown in the Node1 class, or are there any objections to this? Or are there no arguments in favor of why one is better than the other?
oop
Hilbrand bouwkamp
source share