I have a class representing a domain object that contains many calculated properties. Most calculations depend on other properties, which are also calculated. In its simplest form, an example class might 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 leaves me with the following problems:
- This is inefficient because some calculations (some of which are long) are called repeatedly.
- It is difficult to isolate unit tests of individual calculations without providing all the necessary inputs for all dependent calculations to work in the first place.
- It is difficult to obtain from persistence efficiently (I use NHibernate) because, although the calculated data can be stored in the database, it does not receive the extraction and is instead recounted whenever the object is read.
- It is difficult to add calculations, as unit tests grow more and more with the required inputs.
I experimented using a calculator object and a strategy template to set internal fields for properties, but in the end I have a control function too long to make the calculations happen. In addition, moving all calculations to another object turns the original object into an anemic domain object, which I continue to read, should be avoided.
What design patterns and class structure should be used to solve the above problems?
thanks
source share