toasteroven
toasteroven

Reputation: 2790

should a tree node have a pointer to its containing tree?

I'm building a gui component that has a tree-based data model (e.g. folder structure in the file system). so the gui component basically has a collection of trees, which are just Node objects that have a key, reference to a piece of the gui component (so you can assign values to the Node object and it in turn updates the gui), and a collection of Node children.

one thing I'd like to do is be able to set "styles" that apply to each level of nodes (e.g. all top-level nodes are bold, all level-2 nodes are italic, etc). so I added this to the gui component object. to add nodes, you call AddChild on a Node object. I would like to apply the style here, since upon adding the node I know what level the node is.

problem is, the style info is only in the containing object (the gui object), so the Node doesn't know about it. I could add a "pointer" within each Node to the gui object, but that seems somehow wrong...or I could hide the Nodes and make the user only be able to add nodes through the gui object, e.g. gui.AddNode(Node new_node, Node parent), which seems inelegant.

is there a nicer design for this that I'm missing, or are the couple of ways I mentioned not really that bad?

Upvotes: 0

Views: 578

Answers (3)

Patrick McDonald
Patrick McDonald

Reputation: 65471

I see no reason why you should not have a reference to the GUI object in the node. A node cannot exist outside the GUI object, and it is useful to be able to easily find the GUI object a node is contained in.

You may not want to tie the formatting to the level the node is at if your leaf nodes may be at different levels.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273844

It seems to me that the only thing you need is a Level property on the nodes, and use that when rendering a Node through the GUI object.

But it matters whether your Tree elements are Presentation agnostic like XmlNode or GUI oriented like Windows.Forms.TreeNode. The latter has a TreeView property and there is nothing wrong with that.

Upvotes: 2

John Fisher
John Fisher

Reputation: 22727

Adding a ParentNode property to each node is "not really that bad". In fact, it's rather common. Apparently you didn't add that property because you didn't need it originally. Now you need it, so you have good reason to add it.

Alternates include:

  • Writing a function to find the parent of a child, which is processor intensive.
  • Adding a separate class of some sort which will cache parent-child relationships, which is a total waste of effort and memory.

Essentially, adding that one pointer into an existing class is a choice to use memory to cache the parent value instead of using processor time to find it. That appears to be a good choice in this situation.

Upvotes: 3

Related Questions