Question

Perhaps properties aren't the way to go with this, but I'm struggling to find an answer as for a good solution.

public class Blah
{
    public double A { get{ return _B / _C; } }
    public double B
    {
        get{ return _A * _C; }
        set{ _B = value; }
    }
    public double C
    {
        get{ return _B / _A; }
        set{ _C = value; }
    }

    private double _A;
    private double _B;
    private double _C;

    public Blah(){}

    public Blah(double a, double b, double c)
    {
        this._A = a;
        this._B = b;
        this._C = c;
    }
}

Assuming A is always a read-only property, what's a good way to go about handling an arbitrary amount of additional properties that may affect the output of A? I feel this is a bad (completely wrong!) way to do this because I should always be able to retrieve a value I assign. For example, if I assign B = 3, then I should be able to get 3 the next time I call B instead of getting _A * _C.

However, I need for this type of interdependence to exist (or a completely different approach that achieves the same goal). All of the values are related, so I need for the change of one value to be reflected in the others.

I just can't figure out the appropriate way to do this.

Edit

I made a bad example. In reality, the non-A values aren't dependent on A, but only each other -- B affects C, C affects D, etc; however, A is just some combination of those values. Not sure if that matters as for how to best approach this, but thought it was worth mentioning.

Was it helpful?

Solution

It seems that calling it property A doesn't really describe it well. If you had a method that was called SolveForA(), it would make a lot more sense. Same for the others. Using WriteOnly properties still might make sense, but I'd make those methods as well.

OTHER TIPS

In my opinion in presented example properties are misused. You already noticed that we can expect that if we will set value, we will be able also to get the same value. If refactoring of the code would be my job, I think I would like to start from something like:

public class Blah
{
    public double A { get; private set; }
    public double B { get; set; }
    public double C { get; set; }

    public double CalculateB()
    {
       ...
    }

    public double CalculateC()
    {
       ...
    }

    public Blah(){}

    public Blah(double b, double c)
    {
        this._B = b;
        this._C = c;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top