Design patterns for dependent calculated properties in a class?

c#, design-patterns, nhibernate

Solution

Do the work on the write path, not the read path. Then you can populate the latest cached values from a persistence layer without worrying.

So when value A gets written, all calculations that depend on A are redone.

This scheme works great where the number of reads is greater than the number of writes.

Problem

I have a class representing a domain entity that contains many calculated properties. Most of the calculations depend upon other properties that are also calculated. In it's simplest form an example of the class could look something like this. ``` public class AnalysisEntity { public decimal InputA { get; set; } public decimal InputB { get; set; } public decimal InputC { get; set; } public decimal CalculatedValueA { get { return InputA * InputC; } } public decimal CalculatedValueB { get { decimal factor = FactorGenerator.ExpensiveOperation(); return CalculatedValueA / factor; } } public decimal CalculatedValueC { get { return InputA * InputB; } } public decimal CalculatedValueD { get { return (CalculatedValueA * InputB) / CalculatedValueB; } } public decimal CalculatedValueE { get { return CalculatedValueD / aConstant; } } } ``` However, this solution is leaving me with the following problems: - It is inefficient in that some of the calculations (some of which are lengthy) are getting repeatedly called. - It is difficult to unit test individual calculations in isolation without providing all the required inputs for all the dependent calculations to work first. - It is difficult to retrieve from persistence efficiently (I am using NHibernate) because even though the calculated data can be stored to the database, it doesn't get retrieved and is instead recalculated whenever the object is read. - It is difficult to add calculations as the unit tests grow larger and larger with the required inputs. I have experimented with using a calculator object and the strategy pattern to set internal fields for the properties but I am ending up with an overly long controlling function to force the calculations to occur. Also moving all the calculations out to another object turns the original entity into an anaemic domain object that I keep reading should be avoided. What design patterns and class structure should I use to address the above problems? Thanks

Original source