Rafael has posted 5 posts at DZone. You can read more from them at their website. View Full User Profile

Domain Driven Design: Domain Services or Method on an Entity?

07.07.2008
| 11825 views |
  • submit to reddit

There has been much discussion on the DDD list regarding where to put the business logic control, whether in a service or entity. Being more specific, in order to ship an order, the following things should happen:

  1. Validate that the order can be shipped
  2. Update quantity
  3. Set the status to shipped
  4. Save the order
  5. Send an email to the customer that the order has been shipped

 

So, the following Java code snippets were suggested:

  1. Everything in the domain:

public class Order
{
private IOrderShippedNotificationPolicy notificationPolicy;
private IOrderRepository orderRepository;

public void ship()
{
if (!checkIfOkayToShip())
{
throw new InvalidObjectException();
}
updateQuantity();
orderRepository.add(this);
notificationPolicy.notify(this);
}
}

private class OrderShippedNotifyByEmailPolicy implements INotificationPolicy
{
// The object that gets injected is implemented
// in the infrastructure layer
private IEmailGateway emailGateway;

public void send(Order this)
{
// Create email here
emailGateway.send(email);
}
}

 

2. Or have an application service coordinate:

  public class OrderService
{
// orderRepository and orderShippedNotificationPolicy
// are injected dependencies
public void shipOrder(Order order)
{
order.ship(); // in this case it only validates and updates quantity
orderRepository.save(order);
orderShippedNotificationPolicy.notify(order);
}
}

 

There's been a lot of replies also. I highlighted the interesting ones:

"The advantage of the latter scenario is that you're calling _orderRepository. Save in the application layer, which I prefer since it's easier to see the transactional control. The problem with the latter scenario is that it seems it's putting things in the application layer which don't need to be there. The action to Ship() seems to me an atomic, domain centered action and should therefore sit in the domain. I consider the application layer to be like a thin domain facade as defined by Fowler. That is, it is only there to direct/coordinate domain activities. Like I said, Ship() seems like it should be considered one activity, and therefore coordination from a service layer shouldn't be necessary."

"The way I look at it - what needs to go into Ship() is the stuff that _must_ happen before shipping can happen. And shipping can happen without the notification part. You only have a rule that says "send a notification to the customer upon shipping the order". You don't have a rule that says "make sure the customer gets the notification or there are no shipments".

"So, perhaps as a rough, preliminary rule we can say anything which affects the state of the domain should go be placed in the domain. (Of course, the application layer can affect the state of the domain, but only by using domain items to do so maybe think of it as the Law of Demeter among layers.) The email doesn't have any meaning within the domain - it's simply a reflection of the domain."

"Notificitation of an order and the order itself is two separate concepts."

"This could as easily be implemented using AOP."

 

IMHO, I wouldn't have designed it on the domain layer, because I want transactional control on the application service layer. I think the domain has to deal with its particularities, not with sending email or adding things to a repository, even being decoupled of theirs implementations (the domain has a reference only to interfaces). So I prefer the latter approach. And you? What are yout thoughts about this design? How would you have designed it? Everything on the domain or have an application service coordinating the activities?

 From http://rnaufal.livejournal.com
Published at DZone with permission of its author, Rafael Naufal.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Dimitris Menounos replied on Thu, 2008/09/25 - 3:11am

One thing to take into account is the nature of entities to penetrate verticaly through application layers, begining from the datastore and reaching up to the client. As such they may jump in and out of the java enviroment via serialization. This means that if you put your service methods in your entities, they wont be available from the outside world with an easy and reasonable way (think older EJBs).

With this in mind, personaly I prefer to keep the service methods seperate from the entities. This gives me the following benefits:

  • A single set of domain types (entities) that is reusable across many layers
  • A uniform programming model independent of the enviroment
  • A staless and easily scalable services layer

 
PS. With the term entities, I mean the domain data types an application uses in general. These can be defined and exist into many forms like POJOs, XML, JSON etc.

Brian Sayatovic replied on Mon, 2008/07/07 - 9:51am

One way of looking at OO modelling is through the real world.  In the real world, orders don't ship themselves.  The shipping department does.  The order contains the manifest, destination, etc.  But its just a command.

Of course, you shouldn't model your application components after the physical world.  But from the little thought experiement, I would say an Order object might need ship itself.  To do so means the Order would become a hub of dependencies between FulfillmentServices (e.g. FedEx, UPS web services), InventorySubsystem, etc.  It might be better to have an OrderProcessingService manage the processing of orders.

Mind you, my colleagues and I have struggled with this very same thing (we call it the "cake/oven bake" problem -- does the cake ake itself with an oven, or does the oven bake a cake, or does the Bakery bake with an oven and a cake?).  I've even recently gone down the other path -- smarter, more collaborative entities.  The dependency injection did start to become a problem (albeit a fun one!).  yet the semantics of the resulting API were very attractive and easy to follow.

So I, like you , am torn.

Srini Penchikala replied on Tue, 2008/07/08 - 5:29pm

Where to store business logic in a domain driven design application is always an interesting discussion topic, especially when it comes to what goes in an Entity v. what goes into a Service class. I recently published an article to talk about some of the practical considerations of a DDD application. Here is the link to the article.

Alex(JAlexoid) ... replied on Tue, 2008/07/08 - 8:01pm in response to: Brian Sayatovic

[quote]Of course, you shouldn't model your application components after the physical world.[/quote]

Now heres a good question. Why exactly you shouldn't?

Brian Sayatovic replied on Tue, 2008/07/08 - 10:34pm in response to: Alex(JAlexoid) Panzin

[quote=jalexoid]

[quote]Of course, you shouldn't model your application components after the physical world.[/quote]

Now heres a good question. Why exactly you shouldn't?

[/quote] What I mean is, you shouldn't exclusively model your application components after the physical world. I can think of two reasons. First, you may model too much. Second, you may miss out on non-physical-world things. By modeling too much, I mean you may start to model concepts that are beyond the scope of the system, or at least too fine-grained for the needed solution. When modeling the baking of a cake, do you care to model the chemical and physical process occurring in the heated oven? Perhaps if your goal is to simulate the baking of various materials, but for managing a bakery, probably not. Or, is it important to model t he supply chain of your bakery's resources (e.g. flour vendors, egg vendors, etc.) instead of just modeling the bakery's inventory? Second, OO is a powerful paradigm and you may find cause to use it for things well beyond just your modeling of the physical world. For example, a cache can be very nicely implemented as an object even though it is a technical concern of the system reflecting nothing in the physical world.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.