A quick disclaimer: we're entering religious territory here. I feel strongly about this issue, but it's certainly my opinion. If you want to get the full sense of how passionate people are about this issue, check out this article at JavaWorld.
I've come to the point of view that Entities should not use set mutators ("setters"). Anything you represent as a setter can usually be better represented as a plain old method. Why?
Let's remember one of the fundamental guidelines of DDD: intention revealing interfaces. Which is more intention revealing?
Customer c = new Customers().Find(42);
// This...
c.Address = aNewAddressValueObject;
// or this?
c.ChangeAddress(aNewAddressValueObject);
That's a subtle point and it's admittedly open for debate. To firm up my argument let's consider the situation where I'm crunching knowledge into model and address change becomes a temporal concept. I now need to track what an address is of a certain date and time. Surely a setter will do the trick, but I think the command "change an address" is better expressed with a method. I can fiddle with the internals of that method and, because we're practicing command-query separation, accept that commands change the state of aggregate roots and entities.
For me, the biggest argument for avoiding setters is that it promotes thinking in terms of data in a paradigm (DDD) where data-first can be harmful and counter productive. I cannot stress enough: entities are behavioral objects and, for my money, Action<T> where T is some value object fits the notion of command rather elegantly.
Posted
Tue, Jul 8 2008 10:11 PM
by
Dave Laribee