Where to create Value Objects in CQRS & DDD flow

1.9k Views Asked by At

I am struggling with construction of ValueObjects during life cycle of a command.

Here is my situation:

  1. Command Request comes to controller action.
  2. Create command object with request params.
  3. Pass command object to app service
  4. Command handler first validate command attributes
  5. then create aggregate and pass command attributes to aggregate function.
  6. and aggregate function pass attributes to domain event.

My question is where I should put Object Creation logic. or in other words which component of DDD is responsible for initialisation of Objects (Value Objects, Entities etc.) for Aggregates to work with?

2

There are 2 best solutions below

1
VoiceOfUnreason On BEST ANSWER

My question is where I should put Object Creation logic. or in other words which component of DDD is responsible for initialisation of Objects (Value Objects, Entities etc.) for Aggregates to work with?

The usual answer is that domain object creation happens via "factories" (see Evans, chapter 6), that are usually exported from the domain model and invoked by the application code that needs them.

A factory might be an object in its own right, or it just be a function, or even a constructor.

A review of the DDDSample by Citerus might help illustrate:

https://github.com/citerus/dddsample-core/blob/master/src/main/java/se/citerus/dddsample/interfaces/booking/web/CargoAdminController.java#L133

Here, the controller extracts the necessary data (as primitives) and passes that information toward the changeDestination logic.

https://github.com/citerus/dddsample-core/blob/master/src/main/java/se/citerus/dddsample/interfaces/booking/facade/internal/BookingServiceFacadeImpl.java#L74

At the next class in, the Strings are replaced with Value Objects; the TrackingId constructor and the UnLocode constructor implement the factory role in this case. The value objects are then passed toward the changeDestination logic.

0
Meysam Zarei On

You can delegate the creation of domain-models in other services, Actually, they are part of domain-services. you can pass some primitive data or DTO to them and finally, you can expect the valid domain-model from theirs. The common patterns that I can mention are the Factory Pattern or Builder Pattern, usually, they use the domain model's protected constructor to create the new domain model. Notice that your domain model's constructor should be Package Protected and just your domain services can create your domain models. it means that your domain model's constructor shouldn't be accessible from out of your core domain and for creating the domain models you can inject the domain services (factories, builders) to the usecases or application services.