Search code examples
entitydomain-driven-designaggregaterootvalue-objects

DDD shared entity between two aggregate roots


I'm working with two different aggregate roots: Post and Question. Both of them have a Category.

So far I have implemented it as a shared entity (which I'm not sure if is a correct design in DDD).

public class Post
{
    public Guid Id { get; private set; }

    public Category Category { get; private set; }

    public string Title { get; private set; }

    public string Body { get; private set; }
}

public class Question
{
    public Guid Id { get; private set; } 

    public Category Category { get; private set; }

    public string Title { get; private set; }

    public string Body { get; private set; }
}

public class Category
{
    public int Id { get; private set; }

    public string Name { get; private set; }

    public string Key { get; private set; }
}

Note: I'm aware I'm falling into primitive obsession anti-pattern, and I have plans on refactor the primitives into ValueObjects.

After read this post DDD: Share entity with multiple aggregate roots I'm thinking that maybe I should convert the Category in a ValueObject (with multiple fields).

In theory Category could be an Entity with its own lifecycle, but reality is that I don't really add/remove/update categories.

Is it possible to use a shared Entity on DDD? Or I better rather use a ValueObject?


Solution

  • The main question of Entity vs ValueObject is would two instances of the Category with the same values need to be tracked differently? The classic example is a dollar bill - in most instances, the serial number (ID) doesn't matter, and one dollar is the same as another (ValueObject). If your domain is collecting rare bills, though, that would change.

    I'd suspect not in your case, since it appears Category is really just comprised of the name and key. If the Category of a Post changes, do you need to track what the Category previous was?