Inter-dependent properties

The simple way to model that is to have one Independent and one Dependent:

private Independent<int> _x = new Independent<int>();
private Dependent<int> _y;
 
public MyClass()
{
  _y = new Dependent<int>(() => _x.Value*_x.Value + 2);
}
 
public int X
{
  get { return _x.Value; }
  set { _x.Value = value; }
}
 
public int Y
{
  get { return _y.Value; }
  set { _x.Value = Math.Sqrt(value-2); }
}

This will calculate the inverse immediately, and then calculate Y only when it is out-of-date. Then it will cache the value for the next get.

There is a more complex way to model that situation if you anticipate that the inverse will be costly to calculate and rarely used. You could have an Independent switch.

private Independent<bool> _userHasSpecifiedX = new Independent<bool>();
private Independent<int> _usersX = new Independent<bool>();
private Independent<int> _usersY = new Independent<bool>();
 
private Dependent<int> _x;
private Dependent<int> _y;
 
public MyClass()
{
  _x = new Dependent<int>(() => _userHasSpecifiedX
    ? _usersX.Value
    : Math.Sqrt(_usersY.Value-2));

  _y = new Dependent<int>(() => _userHasSpecifiedX
    ? _usersX.Value*_usersX.Value + 2
    : _usersY.Value);
}
 
public int X
{
  get { return _x.Value; }
  set { _usersX.Value = value; _userHasSpecifiedX.Value = true; }
}
 
public int Y
{
  get { return _y.Value; }
  set { _usersY.Value = value; _userHasSpecifiedX.Value = false; }
}

When the switch is true, then _y depends upon _usersX. When it is false, _x depends upon _usersY. Again, the calculation is only performed once when the values are out-of-date, and then cached until the values change again.

Reply

By submitting this form, you accept the Mollom privacy policy.