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:
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
Which design pattern ensures that only one object of particular class gets created? Explanation: Singleton pattern involves a single class which is responsible to create an object while making sure that only one object gets created.
Factory Method is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.
Use prototype pattern when a system should be independent of how its products are created, composed and represented and: When the class to be instantiated is specified at runtime or. To avoid building a hierarchy of factory classes or. It is more convenient to clone an object rather than creating a new object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With