Hisham Hafeel
Hisham Hafeel

Reputation: 121

How to validate domain objects in DDD architecture?

I have found different ways of modelling the Domain Driven Architecture from different sources. But as a best practice, is it best to place the validations of an object in it's property setters keeping the setters private? Or to make the property itself private and perform validations in the constructor?

private string _lastName;
public string LastName
{
      get 
      {
        return this._lastName;
      }
      set
      {
        if(value == null)
        {
          return;
          //or throw exception
        } 

        _lastName = value;
      } 

Please correct me if I am wrong in any way.

Upvotes: 1

Views: 1226

Answers (1)

Deivydas Voroneckis
Deivydas Voroneckis

Reputation: 2513

In my experience, initially properties by DDD should be set in constructor and have private set method with validation inside(if required, some more complicated validations can be done in constructor (if it requires passing services etc.)).

If your domain logic requires to update some properties after object is created, you have two options:

  1. Add Method UpdateMyProperty()
  2. Use the same property with public setter public MyProperty{public get; public set;}

it depends on how complicated your domain logic is. If it requires other services use option 1 because you can pass services as arguments. If it is just a simple value update, use option 2

Upvotes: 2

Related Questions