views:

110

answers:

2

Where does the logic for deleting/not deleting dependent objects belong in DDD?

For instance one has a category that contains products:

class Category
{
    IList<Products> products;
}

A rule might be that a category cannot be deleted unless it has no products.

Where does the logic belong that does the check for no products under this category before deleting it?

  • Domain classes - It appears to be business logic so I would surmise that it belong in the domain layer.
  • Repository classes - The repository layer handles persistence, it has the general CRUD methods, including one for deleting, does the logic belong in this layer?
  • Another solution?
+1  A: 

It's important to remember that like most ideas about software design, DDD is a set of guidelines, not hard and fast rules, so don't worry TOO much about whether or not what you're doing is real DDD. Like most software scenarios, the answer is, "It depends."

In this scenario, consider using a Specification.

Category category; // some category you're working with.
ICategoryRepository _categoryRepository; // some repository.

ISpecification readyForRemoval = new ReadyForRemovalSpecification();

if (readyForRemoval.IsSatisfiedBy(category)
{
  _categoryRepository.Remove(category);
}

public class ReadyForRemovalSpecification : ISpecification<Category>
{
  public bool IsSatisfiedBy(Category category)
  {
    return (category.HasProducts == false);
    // return category.Products.Count = 0; // whatever...
  }
}
Kevin Swiber
"return !category.HasProducts;" perhaps?
Bryan Watts
Kevin Swiber
A: 

Usually, the aggregate root will manage lifetime of child entities.

Think Before Coding