Well about a week or two ago I made a thread about anemic domain models. The fact is that the term ‘anemic’ is relative, if you remove a part of the domain logic from a rich model the model becomes more anemic, but it may still be a rich model overall. On this aspect, the balance of business logic in domain models and service objects becomes an interesting follow-up topic. Still, I see no justification for completely anemic domain models, I mean those that have absolutely no domain logic. If service objects exist, they need to handle special business logic that is somewhat difficult or cumbersome for domain models to manage themselves.
So what do you think about this? What kinds of business logic are better off handled by service objects rather than domain models themselves? One reason to place business logic in service objects over domain models that I can think of, is an operation that requires interaction between two domain models that do not have an owning-dependent relationship. For domain logic on primitive values and value objects(such as money), they should go to domain models unless there is a good justification for not doing this way.
For instance, if I have an itemshop system and an alchemy system on my site. In the case of alchemy, a new item object is created by applying business logic on two or more items to mix them together if certain criteria are met. The reason for a service object is that its difficult to figure out whether this business logic belong to the first ingredient item, the second ingredient item or the others. To solve this problem, we use a service object that simply alters the states of all the items without them being aware of each other’s existence. Similarly, if you have a bat and ball from a tennis game, its difficult to tell if the domain logic of collision handling should belong to the ball or the bat. Here a service object services as a mediator, it handles collision service so neither the ball nor the bat will take on this controversial responsibility on its own. Of course there is an exception to the rule as I mentioned before, that is when the two domain objects clearly have an owning-dependent relationship. Lets say a shop selling items, the shop owns a collection of items and is obviously aware of the existence of the items. The domain logic of calculating item prices given a shop’s sales tax and the action of selling items should belong to the shop object then.
I know it is hard to generalize, but the idea is that in a good software the business logic in domain models and service objects is in a healthy balance, even if the application is mostly CRUD operations. I still do not have a rule of thumb of how much percentage of domain logic should go to domain models compared to service objects to make a good application though, perhaps I will find out by real practices. Whats your thoughts?