DDD: create Value objects inside an aggregate or pass it as a parameter?

When creating aggregates, we must create value objects inside the aggregates or we must transfer already created value objects to ctor or factory.

public Booking(DateTime arrivalDate, DateTime departureDate) { this.ArrivalAndDepartureinformation = new ArrivalAndDepartureInfo(arrivalDate, departureDate); } 

or

  public Booking(ArrivalAndDepartureinformation arrivalAndDepartureInfo) { this.ArrivalAndDepartureinformation = arrivalAndDepartureInfo; } 
+5
source share
3 answers

Create Value objects inside an aggregate or pass it as a parameter?

  • If we are talking about passing parameters to the constructor, it depends on how it is used. There may be some infrastructure limitations that may require the use of primitive types.

  • If we are talking about passing parameters to methods, then Value Objects are 100% of my choice.

In general, I would say that it is better to pass value objects to their aggregates .

Value objects can:

  • make your model language more expressive
  • bring security type
  • encapsulate validation rules
  • own behavior
+3
source

The domain model should point to the domain, and not to implementation primitives.

Typically, your application component is responsible for obtaining the raw data and its expression in the model language.

+3
source

The general rule that I would recommend is as follows:

  • Within the domain model, make the most of value objects.
  • Conversion of primitives to value objects at the domain model boundary (controllers, application services).

For example, instead:

 public void Process(string oldEmail, string newEmail) { Result<Email> oldEmailResult = Email.Create(oldEmail); Result<Email> newEmailResult = Email.Create(newEmail); if (oldEmailResult.Failure || newEmailResult.Failure) return; string oldEmailValue = oldEmailResult.Value; Customer customer = GetCustomerByEmail(oldEmailValue); customer.Email = newEmailResult.Value; } 

Do it:

 public void Process(Email oldEmail, Email newEmail) { Customer customer = GetCustomerByEmail(oldEmail); customer.Email = newEmail; } 
+2
source

All Articles