First, it is unclear what you mean by total
. On the one had you said it is a property, and then you also said it is calculated based on the value of its children. What that implies to me is that there are really two different properties that you have. One is value
which is usually (always?) zero for entities with children, and one that is total
which is calculated property based on the sum of its own value
plus the value
of all of its children and their children etc. I suspect that this is the main idea that is tripping you up.
The second issue is efficiency for calculated the total
which can be a long recursive process. First, don't try to preoptimize. If your graph is only a few deep, it is quite possible that calculating the value when needed is not a long process. If, and only if, you find that it is is talking to long and think that the best way is to have total precalcuated in the graph it should not be that hard.
- Have one place where nodes are inserted, removed or their values change. All changes in the application go to that one place.
- When a node is inserted go up the graph and add its value to all of its parents'
total
property
- When a node is removed go up the graph and remove its value from all of its parents'
total
property
- when a node's value is changed go up the graph and subtract the difference from the old value to the new value from all of its parents'
total
property