LoremIpsum
LoremIpsum

Reputation: 1862

How to figure out whether a business action(method) should reside in domain object(class) or domain service(class)?

According to "Domain Driven Design",domain service encapsulates business logic that doesn't naturally fit within a domain object.The definition of domain service is clear,but how can i distinguish whether a business action belong to a domain object or domain service.For example i have a Account class,and a business action call transfer,both domain service and domain object can finish the transfer task.which one should i choose?

public class Account
{
  public void Transfer(Account bar)
  {
     //do something
  }
}
public class AccountService
{
  public void Transfer(Account foo,Account bar)
  {
     //do something
  }
}

Upvotes: 1

Views: 88

Answers (2)

Stephan Eggermont
Stephan Eggermont

Reputation: 15907

Transfering money is a natural responsibility of the Account. It might need helper objects with that. Objects should be active, not passive data holders.

Upvotes: 0

In "Domain Driven Design" Eric Evans states:

When a significant process or transformation in the domain is not a natural responsibility of an ENTITY or VALUE OBJECT, add an operation to the model as a standalone interface declared as a SERVICE.

Probably the most important point here is natural responsibility.

Since transferring money from one account to another is not the actual responsibility of an account, I would go for the service approach.

This gets even clearer if other actions might be related to the transfer. The responsibility of the Account class is to encapsulate related data.

Examples for Account responsibilities are:

  • tell the current balance (e.g. is it negative?)
  • tell if the account is closed
  • tell who is the owner
  • increase or decrease the balance
  • show the history of balance changes

Note that all these responsibilities only refer to the object itself or its associated or aggregated objects.

Upvotes: 1

Related Questions