Using properties vs. methods for calculating changing values

Go To


Is there a convention for whether or not to use a property to calculate a value on call? For instance if my class contains a list of integers and I have a property Average, the average will possibly change when an integer is added/removed/modified from the list, does doing something like this:

    private int? _ave = null;
    public int Average
            if (_ave == null )
                double accum = 0;
                foreach (int i in myList)
                    accum += i;
                _ave = accum / myList.Count;
                return (int)_ave;
                return (int)_ave;

where _ave is set to null if myList is modified in a way that may change the average...

Have any conventional advantage/disadvantage over a method call to average?

I am basically just wondering what the conventions are for this, as I am creating a class that has specific properties that may only be calculated once. I like the idea of the classes that access these properties to be able to access the property vs. a method (as it seems more readable IMO, to treat something like average as a property rather than a method), but I can see where this might get convoluted, especially in making sure that _ave is set to null appropriately.

2012-02-29 21:31
by NominSim
It should be fast, not produce any side effects, and never throw - asawyer 2012-02-29 21:37
Bear in mind also that for certain operations (like the Average as you have shown above) if you are using a List structure it already has an extension method to provide you with this value - JayP 2012-02-29 21:41
@JayP Yeah I know, my code involves a more complex property involving particular occurrences of certain objects in a more verbose list, but the average example seemed to be sufficient to simplify the question without bogging it down in unnecessary details - NominSim 2012-02-29 21:43


The conventions are:

  • If the call is going to take significantly more time than simply reading a field and copying the value in it, make it a method. Properties should be fast.
  • If the member represents an action or an ability of the class, make it a method.
  • If the call to the getter mutates state, make it a method. Properties are invoked automatically in the debugger, and it is extremely confusing to have the debugger introducing mutations in your program as you debug it.
  • If the call is not robust in the face of being called at unusual times then make it a method. Properties need to continue to work when in used in constructors and finalizers, for example. Again, think about the debugger; if you are debugging a constructor then it should be OK for you to examine a property in the debugger even if it has not actually been initialized yet.
  • If the call can fail then make it a method. Properties should not throw exceptions.

In your specific case, it is borderline. You are performing a potentially lengthy operation the first time and then caching the result, so the amortized time is likely to be very fast even if the worst-case time is slow. You are mutating state, but again, in quite a non-destructive way. It seems like you could characterize it as a property of a set rather than an "ability" of the set. I would personally be inclined to make this a method but I would not push back very hard if you had a good reason to make it a property.

Regarding your specific implementation: I would be much more inclined to use a 64 bit integer as the accumulator rather than a 64 bit double; the double only has 53 bits of integer precision compared to the 64 bits of a long.

2012-02-29 21:37
by Eric Lippert
I completely agree with this, but what happens in the case when "most of the time" the call is quick(i.e. it has already been computed), but "occasionally" i.e. on certain changes to the object it must be computed again, that's what I am struggling with - NominSim 2012-02-29 21:41
@NominSim: I've added some additional thoughts - Eric Lippert 2012-02-29 21:45
Thanks, yeah I threw together the "Average" example as just that, an example, so as to not bog down the question with unnecessary details, my property involves a similar idea of a possibly lengthy initial computation, followed by many subsequent calls for the already computed value(interrupted possibly by rare changes that require the value to be recalculated - NominSim 2012-02-29 21:49


Microsoft's recommendation to using methods:

Use method

  • If calling has side effects
  • If it returns different values each calls
  • If it takes long time to call
  • If operation requires parameters (except indexers)

Use property if calculated value is attribute of object.

In your case I think property with implicit lazy calculation would be good choice.

2012-02-29 21:37
by STO


Yes there is... a get accessor should not in any way modify the state of the object. The returned value could be calculated of course, and you might have a ton of code in there. But simply accessing a value should not affect the state of the containing instance at all.

In this particular case, why not calculate everything upon construction of the class instance instead? Or provide a dedicated method to force the class to do so.

Now I suppose there might be very specific situations where that sort of behavior is OK. This might be one of those. But without seeing the rest of the code (and the way it is used), it's impossible to tell.

2012-02-29 21:36
by kprobst
It was really the amount/degree of code within the get accessor that I was questioning, obviously a get accessor shouldn't modify the state of the object - NominSim 2012-02-29 21:38

Yes there is... a get accessor should not in any way modify the state of the object.

The only exception is lazy calculation - when result of calculation is stored in an object's field and then used in further calls - STO 2012-02-29 21:39

Also I can add, that properties are designed to immediately return values, so when you call something like .Average you suppose that it is already calculated. And you will never suppose that this property is actually doing something. So methods are actions that do something, and properties just return computed values. But, there could be properties that compute smth. if you have some values that could be computed fast, maybe cached, and the developer won't ever notice that these properties are doing something. He will think that they are already computed. Like in this cas - Archeg 2012-02-29 21:41
My question is whether there is a convention for when under most cases the property value won't change and can therefore be immediately returned, but upon initial calculation (and the rare re-calculations) it may take some time - NominSim 2012-02-29 21:47