patterncsharpMinor
C# Extension Properties
Viewed 0 times
propertiesextensionstackoverflow
Problem
I am doing some math - combining, reusing, extending different analyses methods over the same original data set. It would be reasonable to use C# extension methods in my case instead of defining everything in one class. The same time there are too much stuff to be constantly recalculated in this extension methods - I definitely need something like extension write-once/calculated-once extension property mechanism. Here is how it looks like and how to consume it. Please comment on this if anything smells for you (sources are on GitHub).
Let's imagine that we have class
To extend it with couple properties:
We define:
where
We define
Let's imagine that we have class
Person:namespace People
{
class Person
{
}
}To extend it with couple properties:
Name- write-once extension property
Salutation- calculated-once extension property
We define:
namespace HumanResource
{
using People;
using ExtensionProperties;
static class ContactInfoProperties
{
static readonly ExtensionProperty NameProperty =
new ExtensionProperty();
static readonly ExtensionProperty SalutationProperty =
new ExtensionProperty();
public static string Name(this Person person, string name) =>
person.Add(NameProperty, name);
public static string Name(this Person person) =>
person.Get(NameProperty);
public static string Salutation(this Person person) =>
person.GetOrAdd(SalutationProperty, () => "Hello " + person.Name());
}
}where
ExtensionProperty and three extension methods Add, Get, GetOrAdd are being imported from ExtensionProperties namespace.We define
ExtensionProperty fields to uniquely identify property identity and type for the storage system. Add method adds property value to the storage. It throws RedefinedPropertyException if value has been already associated with the property.Get method tries to read value from the storage or throws UndefinedPropertyException if values is missing.GetOrAdd methSolution
- API in your example is really confusing, since you use
Namemethod to both set and get property value. You should make your intent clear, by using, say,GetNameandSetNamefor method names.
- You should probably add
T Valueproperty to yourExtensionPropertyclass, and use it to store the value, instead ofConcurrentDictionary. I think it will make more sense.
IExtensionPropertyinterface is awkward. I think you can do just fine without it.
- Finally, imho, you are not making a convincing case. Why can't you just create a regular class (or classes) to analyze data and another class (or classes) to store the results? Call me old-fashioned, but the idea of using attached properties to analyze data strikes me as a truly horrifying design decision. At least it is not something I am willing to maintain, debug or review. :)
Context
StackExchange Code Review Q#117789, answer score: 4
Revisions (0)
No revisions yet.