I have a more complex structure, where some "child" classes are added to the "parent" class as subview. Thereby I have variable called currentSelectedDate
, which should be accessible in all of the connected classes. My current structure looks like the following:
Class A (top most "parent"):
private DateTime currentSelectedDate;
public DateTime CurrentSelectedDate {
get
{
if (this.dayHeader != null)
{
return this.dayHeader.CurrentSelectedDate;
}
else
{
return this.currentSelectedDate;
}
}
set
{
this.currentSelectedDate = value;
if (this.dayHeader != null)
{
this.dayHeader.CurrentSelectedDate = value;
}
}
}
Class B ("child" of A/dayHeader):
private DateTime currentSelectedDate;
public DateTime CurrentSelectedDate {
get
{
if (this.weekdayScroller != null)
{
return this.weekdayScroller.CurrentSelectedDate;
}
else
{
return this.currentSelectedDate;
}
}
set
{
this.currentSelectedDate = value;
if (this.weekdayScroller != null)
{
this.weekdayScroller.CurrentSelectedDate = value;
}
}
}
Class C ("child" of B / weekdayScroller):
public DateTime CurrentSelectedDate { get; set; }
Here only the direction from the parent to the child is shown, where the properties are used to spread the data. In the backwards direction I use events. The disadvantage of this approach is that I have to store the values multiple times in each class. Also if I'm in one class, I have to set the value of this.currentSelectedDate
, but also in the other class (e.g. dayHeader.CurrentSelectedDate
) manually (the setter/getter should only be used by external calls).
For class A the class C (weekdayScroller) is hidden.
Class C (weekdayScroller) is used by other classes too, so I have to maintain the property currentSelectedDate
directly in it.
One has also to be aware of when something is initialized. E.g. on the creation of class A the currentSelectedDate
is set, but class B isn't existing yet. Therefore the null
checks.
My question now is if this is a good way of handling the spreading of the state between all classes or if there are better ways.
Is there a better way? Not that I am aware of. I understand the drawbacks of this design.
If there is just a single value of the variable to set (so parent-child relation is 1:1), why not put it in a shared class which you reference everywhere. It is virtually the same, but it might be easier to have an overview of what happens where and whose responsibility it is.