2
votes

I'm developing a class that will be used to generate a tree structure. Each Node of the tree needs to know both who it's parent is and who it's children are. The fields used to track each Nodes parent and children are not accessible outside the base Node class.

Right now I have methods for AddChild, and Remove child. Which consequently also set the parent fields of the instances being related.

So what I'm wondering now is if it would be any better or worse to switch this and setup methods where the user of the class has to call Node.SetParent(Node parentNode) and Node.ClearParent(Node oldParentNode) methods instead.

If you are tracking both parent and child relationships, why would you choose to set the child relationships over the parents or vise versa, or does it even matter?

3

3 Answers

1
votes

In either case, when you are attaching a node to the tree you will need a reference to both the parent and the child node in question, so I don't see how it would make a difference, as either way will be equally possible in all situations.

I'd suggest figuring out which direction your logic will make the most sense (i.e. is it easier to think about building the tree from the leaves up or the root down) and go with that.

0
votes

Decisions like these typically depend on how the class will be used. If a typical scenerio is for a tree to be build from the parent node down, then using an AddChild method is often best, if your users build them from the other way around, give the a SetParent method. If there is a need for both, implement both, so long as the appropriate book keeping is done internal to the class.

(side note: I usually build trees from the parent down)

0
votes

I think you need all three methods. When building a tree, the AddChild method would seem more natural. There are two reasons to remove a node. One is to get rid of it, and the other is to reorganise the tree (move a subtree to another branch). When deleting, RemoveChild works well. But reorganisation could use the SetParent method to avoid making two calls. SetParent could also become a transaction of sorts.