I have an object in a hierarchy whose values โโcan have the value of a parent object. Both objects are of the same type.
As an example: if the Score property is double.NaN , then the Score value should be retrieved from the object pointed to by the Parent property, but only if Parent ( Parent != null ) is set.
My question is, how can I reliably and broadly implement such a model? I have 2 options, but maybe there are more?
Option 1: Change each getter and setter property to check if the property has a given or received value, the default value, and if so, try reading it from the parent
private double score = double.NaN; public double Score { get { return (score == double.NaN && Parent != null) ? Parent.Score : score; } set { score = (Parent != null && Parent.Score == value) ? double.NaN : value; } }
Pros:
- real-time atomic updates of all property values โโseparately
- Explicit default comparison
Minuses:
- each getter and setter element must be implemented manually, which may be error prone
- executed with every get and set
Option 2: The default implementation when loading and saving an object
void AfterLoad() { if(Parent != null) { if(score == double.NaN) { score = Parent.Score; }
Pros:
- parent is used only when loading (once) and saving (twice), which improves performance
Minuses:
at any time, changing the parent will not affect child properties
Before and after changing the parent, you must process the child (to return to the new default values โโafter the parent changes)
atomicity may be affected - during storage, the object cannot access any other thread
I am sure that many had a similar dillema when implementing the "styling" model of an object. I am looking for a clean and working solution that will also work with combining collections of child and parent objects together (using CompositeCollection?).
source share