Question

   class Foo
   {
       public List<float> Data { get ; set ; }  // list of numbers
       private float Total { get ; set ; } // Contains sum of numbers in Data

       // Constructors and other stuff.
   }

My code that uses this class keeps modifying Data so I want to see the relevant changes in Total also.

I don't want to add function that recalculates Total to the code that modifies Data.

Example:

   Foo f = new Foo(); // Total = 0 
   f.Data.Add(10);    // Total = 10
   f.Data.Add(30);    // Total = 40
   f[1] = 40;         // Total = 50
   // etc

So What is the solution to this problem ?

Was it helpful?

Solution

Alter you get function to dynamically return the total instead (using linq is easiest):

private float Total
{
   get
   {
      return Data.Sum();
   }
}

No need for a set accessor really.

OTHER TIPS

I don't see the problem here. The Total getter can compute the total of the list dynamically when it is being called, which does not modify the list at all. However, I don't see how you want to implement a setter for the total...

  private float Total { // Contains sum of numbers in Data
    get {
      float total = 0;
      foreach (float value in Data) {
        total += value;
      }
      return total;
    }
  }

You are exposing the Data, it could all be erased at any time, I'd suggest the following:

class Foo
{
    private List<float> _data = new List<float>();
    public float Total {get; private set;}
    public void Add(float f) { _data.Add(f); Total += f; }
}

Add calculation logic to the Total getter:

private float Total
{
  get { return CalculateResult(Data) };
}

This way you do not even need setter. Of course you can cache: introduce dirty flag in a class that is changed when you change Data list. Then cache calculation result that you get in Total getter to a local class field and reuse that if dirty flag is not set (clear it on recalculation).

I think there is no need for the setter in the total property, however the getter simply recalculate the sum for every call

class Foo
   {
       public List<float> Data { get ; set ; }  // list of numbers
       private float Total { get{return Data.Sum()} ; } // Contains sum of numbers in Data


   }

Why do you need setter on Total? The best way is to make Total auto-calculated property and calculate the Total's getter value dynamically.

Or... you can introduce private fields data and total and recalculate total within Data setter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top