I have a class filled with properties. When the properties are accessed it reads some values out of an XDocument.
public class Foo
{
private XDocument root;
public Foo(Stream str)
{
root = XDocument.load(str);
}
public String Bar
{
get
{
return root.Element("bar").Value;
}
}
}
Only it seems a bit of overhead, since everytime it get accessed it has to read the XDocument again. I tried to ‘cache’ this a little bit as following
public String Bar
{
get
{
if(String.IsNullOrEmpty(this.Bar))
return root.Element("bar").Value;
else
return this.Bar;
}
}
This seems pretty decent for me, only I have one problem with it. The class has like ~200 properties. Everytime I have to do this check, and since OOP is all about not copying large parts of code is there any way to make this work like this automatically?
As “thelost” mentioned, don’t have a single field for each property. Keep a dictionary as a cache, so you don’t pay anything for properties you haven’t accessed.
I would suggest you then have a method which you can provide with the mechanism for retrieving the real value. For example:
That way each property ends up reasonably compact – it basically expresses the cache key involved, and how to compute the property. If you need properties of different types, you might want the cache to just have
TValueasobject, and make theFetchmethod generic, casting where necessary. That will end up boxing value types, admittedly.If you use this approach in several places, you may well want to create a generic
ComputingCacheclass to avoid repeating the logic.