Setters in Domain Model
In the context of DDD setters on a domain model are a code smell. They should be avoided for the simple reason that they are not really part of the domain. There are no nouns in it that a Domain Expert may understand and changes to the data should go through specific methods instead.
Example:
customer.StreetName = ...
customer.City = ...
While the right way to do that would be to have a customer.ChangeAddress
method that could then publish an event etc etc.. At least from my understanding this is all sound theory and I can totally understand why setters in a domain model are not really desireable.
BUT: Without setters on your domain model, those methods get pretty hard to test.
How do I get a Customer instance to run my tests against if I can't construct one without having either a big-ass constructor that takes in ALL arguments, or do some reflection magi开发者_Go百科c? I use NHibernate in the backend so NHibernate already does some reflection magic to populate these fields in the first place.
But it feels really bad to have a ctor with 10 arguments.. (And the same would be true for a factory method).
Any advice on this?
greetings Daniel
In classic (non-CQRS) DDD it is a good practice to factor out all the data to Value Objects so that your entities are reduced to their primary function: maintaining identity.
In you example Customer should reference an Address ValueObject and have a ChengeAddress method which would should be as simple as:
public void ChangeAddress(Address address)
{
//Consistency rules are here
_address = address;
}
Try to move as much logic as you can from your entities to your value objects. They are inherently more testable since good value object is small and immutable. You use a constructor to instantiate VO in a given state and exercise it (usually by invoking a method which returns another, transformed, VO instance).
Last but not least, from my experience I can say that if testing your domain model requires additional infrastructure (like reflection or any other tool), you're doing it wrong (by introducing unnecessary coupling).
You might want to try AutoFixture.
Mix in a bit reflection love and domain gets quite testable:
namespace Unit{
using System;
using System.Linq.Expressions;
public static class ObjectExtensions{
public static T Set<T,TProp>(this T o,
Expression<Func<T,TProp>> field,TProp value){
var fn=((MemberExpression)field.Body).Member.Name;
o.GetType().GetProperty(fn).SetValue(o,value,null);
return o;
}
}
}
Usage:
myUberComplexObject.Set(x=>x.PropertyOfIt, newValueOfIt);
And You should at least try to divide those "big-ass" objects into smaller ones. Try to make a hierarchy (just make sure it's compliant with ubiquitous language).
精彩评论