Best practices on calculated properties

  • Thread starter Thread starter The Last Gunslinger
  • Start date Start date
T

The Last Gunslinger

What are peoples views on using readonly properties to return the sum of
a calculation?

For instance you might have a invoice class that has itemprice and
quantity properties.
Would the total be implemented as readonly prop Total to return
itemprice * quantity or method CalculateTotal which returns the same thing.

A readonly prop is, IMHO, more intuitive as it is still an attribute of
this class but what about when you have a longer calculation that
affects performance and as such should be stored by the consumer instead
of running the calc every time they wanted to access the 'property'.

I dont think there is a 'right' way to do this but I need to define a
clear rule for programming standards to be implemented in a company.

Thanks for your input.

JB :)
 
The Last Gunslinger said:
What are peoples views on using readonly properties to return the sum of
a calculation?

For instance you might have a invoice class that has itemprice and
quantity properties.
Would the total be implemented as readonly prop Total to return
itemprice * quantity or method CalculateTotal which returns the same thing.

A readonly prop is, IMHO, more intuitive as it is still an attribute of
this class but what about when you have a longer calculation that
affects performance and as such should be stored by the consumer instead
of running the calc every time they wanted to access the 'property'.

I dont think there is a 'right' way to do this but I need to define a
clear rule for programming standards to be implemented in a company.

I think that your intuition is correct that a property is appropriate for a
simple calculation, and you should expect a property to be accessed multiple
times in quick succession. For a more involved computation I would suggest
either caching the result in a private instance field (and adding
appropriate logic to invalidate it), or using a member function instead of a
property. A function called CalculateTotal suggests a degree of work to do
the Calculating.

Then you can have a simple guideline for both creators and consumers of
types: Allow (Expect) multiple invocations of properties, but not of member
functions.

eg

if (myType.Something == 1)
.. . .
else (myType.Something == 2)
....

but,

int something = myType.GetSomething();
if (something == 1)
.. . .
else (something == 2)
....


David
 
Back
Top