Search code examples
treeumlclass-diagram

What is a proper UML class-diagram for a tree node class with reference to parent and a list of descendants?


Node data is stored in a database where each node record has foreign key field with ID of parent node (if it has one) or NULL. So it seems that node has only one link. But my program reads/writes data to this DB with ORM and for my business logic nodes are represented with the class which has a reference to a parent node and a list of descendants (two links).

//pseudocode
class TreeNode {
  TreeNode Parent
  TreeNode[] Descendants
}

enter image description here or enter image description here

1. What is the correct UML class diagram for this class? Does it have two links or one?

2. Maybe I should use two diagrams (one for DB and one for a class used by ORM)?


Solution

  • There is only one association in this case. If X is a Parent of Y, then Y is Desdendant of X, right? There is only one link, which can be seen from two perspectives.

    The trick is to watch association end roles (which are simply ignored on your diagram).

    So, the roles are as follows:

    • "Parent" (0..1), at the association end with the diamond.
    • "Descendants" (0..n) at the opposite association end

    Here is the final diagram, and an object diagram to make it clear, that there is only one link, that is - only one association: enter image description here

    You can always use 2 diagrams if you wish to show the 2 abstraction layers explicitly. However, I find the effort not justified, because the mapping is clear and straightforward. I think the abstract UML diagram is more than enough; the second one can always be generated.