C#C
C#3mo ago
Giogio

Tree structure vs composition

Trees are common in the application I currently develop. For example there is a tree of machines, where machine has a parent (machine family), the parent can have it's own parent and so on. Both machine and machine family can have parameters, these parameters are inherited from parents, so if a root parent has parameter A, the second parent has parameter B then machine will also contain parameters A and B. There is a lot of business logic attached to these parameters and the problem for me is 1) loading this whole tree structure from the database 2) iterating through parents for parameters. I started wondering, maybe composition will be a better approach. That means that instead of having parent, machine would have a list of parents with indexes (levels).

So instead of this
Machine A
─ Parent 1
─ Parent 2
─ Root parent

I would have this
Machine A
─ Parent 1 (index = 0)
─ Parent 2 (index = 1)
─ Root parent (index = 2)

Then loading all parents and parameters wouldn't be a problem AND iterating through parent's parameters would be easier as well.

Question: What do you think of this, are there hidden problems that I don't see? I never encountered structures like this so I'm a little nervous to implement that.

Some context:
  • Leaf rarely has more that 3-4 parents
  • Item is used either by itself or with every parent recursively
Was this page helpful?