When does logic belong in the Business Object/Entity, and when does it belong in a Service?

巧了我就是萌 提交于 2019-12-04 07:01:38

I would tend to have an external service determine the shipping rate. For me that's application logic rather then order-specific logic. For example you might decide for a period to offer free shipping for orders over a certain size, or to a particular group of loyal customers. For me that logic will tend to change independently of how an order is constructed.

Most likely I would have the code which is responsible for placing the order (some kind of Order Processor service, in an application layer or in a command handler) hand off to a service to get the shipping rate, and then pass that rate into the order, so I guess option 2.

For printing a shipping label, I'd tend towards having the domain raise an event along the lines of http://www.udidahan.com/2009/06/14/domain-events-salvation/. A separate handler would then deal with printing the label. Again, the logic for this is that the way you print labels is likely to vary independently of how you construct an order, so it makes sense to keep that separate. Using a domain event seems to be the cleanest way of ensuring that the label is printed at the right time without requiring the Order (or indeed the order processor) to be aware of the printing logic.

If you are accessing external webservices to get Postage rate, it is better to create interface in Application layer, because evan itself suggested that if you want to talk with external webservices you should construct interface in Application layer, you would have the service implementation injected into your Domain Object. For printing shipping label, because label is printed only when postage rate is determined, so is a kind of event like PostageRateConfirmed your domain can raise this event.

http://danhaywood.com/2010/04/30/accessing-domain-services-from-entities/

I would use (2).

It doesn't add extra complexity to your Order Item.

To me, it seems the natural use of a helper service.

Update: in response to comment: The wiki page states:

Anemic Domain Model: With this pattern, logic is typically implemented in separate classes which transform the state of the domain objects

My point of view: The domain is what contains the logic of your application, without the infrastructure cruft. The logic is that when an order is confirmed a label is printed and the shipping rate is determined. That should be in the domain.

The infrastructure then accomplishes what the domain wants to do. The domain may let the infrastructure know through messaging, or events.

That way no infrastructure leaks into the domain, you only require a way to transport messages out of the domain.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!