Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send domain entity as paremeter or send entity id as parameter in application services

when using domain driven design, is it better that your services' methods receive an entity as parameter or the id of your entity as parameter so that you can retrieve the entity inside the method using a repository?

for example:

public void Apply(Job job, User user)

versus

public void Apply(int jobId, int userId)
like image 940
ryudice Avatar asked Mar 14 '11 23:03

ryudice


2 Answers

DDD is about mapping your client's vocabulary to your design. Your client (hopefully) talks about users applying for jobs, not some integer ID being linked to another integer ID. Try to stick to the real world as close as possible, unless it becomes a burden.

By passing in the entire entity, you can benefit from the entity's behavior immediately, without having to construct it first.

So stick to entities, unless you have a situation where you often only have an ID to work with. This usually happens when you're dealing with external systems, such as web services. In that case you can create a method overload that accepts the ID. This overload should validate the ID, construct the entity and call the overload that accepts the entity.

public void Apply(int jobId, int userId)
{
    // Validate the IDs.

    // Construct the entities.
    var job = ...;
    var user = ...;

    // Call the 'proper' overload.
    Apply(job, user);
}

public void Apply(Job job, User user)
{
    // Actual business logic belongs here.
}

Again: try to avoid such overloads as much as possible, unless you're dealing with external systems that only return the ID.

From a coding point of view, entities are also better than integers. An integer can be of any integer value, so you'd have to validate it everywhere you use it. Your factories are responsible for constructing valid entities and your (domain) logic should keep your entities in a valid state. So using the entity is completely safe and shouldn't require much validation.

like image 171
Niels van der Rest Avatar answered Sep 30 '22 17:09

Niels van der Rest


It depends on where your Application Service resides:

If your Service executes within the same AppDomain (i.e. you're calling it from the same executable), then passing the object is ideal. The Service can easily access other objects within the object graph.

If your Service executes in a different AppDomain (e.g. behind a WebService or other remote location), you should use an ID. The Service would then load the appropriate object from the persistence store before working with it.

If you try to send objects down the wire, you likely run into the problems described here.

Hope that helps.

like image 23
Vijay Patel Avatar answered Sep 30 '22 17:09

Vijay Patel