Domain Model, validation, and pushing errors to the model

domain-driven-designlayersvalidation

Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags. That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}

From a developer's perspective, you could create an empty category, but this isn't valid in the business world. A Category requires a Name to be a valid category, therefore we end up with:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}

Now, a Category can't be created without a name. But, we can't have duplicate Category names either, that would just cause confusing and redundancy. I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place. It is important that if the user types an duplicate Category, we would notify the user of this. Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

Best Answer

I would create a domain service responsible for validating the uniqueness of the category. In my solution domain defines the interface of the service, infrastructural part implements it using a database.

Please also take a look at https://stackoverflow.com/questions/516615/validation-in-a-domain-driven-design.