Thursday, March 18, 2010

Steve Bohlen on Practical DDD in .NET and Value Equality

I recently had the chance to see an excellent presentation by Steve Bohlen on Practical Domain Driven Design. It was given to the Philly ALT.NET user group. He has slides and example code available here. ). For numerous discussion points, he emphasized the range of options available. It was refreshing to hear this approach which wasn’t dogmatic in how to approach DDD.


He talked about his Proteus open source library which has some very useful code in it. I want to illustrate in this post one of the classes he uses for DDD category of classes know as value objects. Value objects don’t have a unique identifier for equality checks. Instead, value objects are equal when all fields match. Steve uses a ValueObject base class that allows any type to have its fields compared using reflection. This allows the creator of a value object to have the functionality of equality comparison without writing out all of the tedious plumbing code to compare two objects field by field and without the code clutter within the class. There is more to his class than this but this is a very significant method.


 public virtual bool Equals(TObject other)  
{
if (other == null)
{
return false;
}
FieldInfo[] fields = base.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo info in fields)
{
object obj2 = info.GetValue(other);
object obj3 = info.GetValue(this);
if (obj2 == null)
{
if (obj3 != null)
{
return false;
}
}
else if (typeof(DateTime).IsAssignableFrom(info.FieldType) || typeof(DateTime?).IsAssignableFrom(info.FieldType))
{
DateTime time = (DateTime) obj2;
string str = time.ToLongDateString();
string str2 = ((DateTime) obj3).ToLongDateString();
if (!str.Equals(str2))
{
return false;
}
}
else if (!obj2.Equals(obj3))
{
return false;
}
}
return true;
}

No comments:

Post a Comment