Search code examples
c#domain-driven-designprimary-keyaggregateroot

DDD: Aggregate root or Entity Key design, Should the key UUID or unique number be generated by the system?


In my business logic, A User can be identified by his/her mobile phone number. 3rd party verification system ensures that the customer's phone number exists in real, and the system checks the uniqueness before insert User record into the table. From my opinion, PhoneNumber is already unique, so Id is unnecessary.

Here is my current User class. PhoneNumber currently is a value object in User class.

    public class User : AggregateRoot<Guid>
    {
        public Guid Id {get; private set;}
        public PhoneNumber PhoneNumber { get; private set; }
        public Birthday Birthday { get; private set; }
        public Gender Gender { get; private set; }
        public Name Name { get; private set; }
    }

I want to change like below.

public class User : AggregateRoot<string>
{
   public string PhoneNumber { get; private set; }
   public Birthday Birthday { get; private set; }
   public Gender Gender { get; private set; }
   public Name Name { get; private set; }
}

Are there any flaws if I use non-UUID Id in an Aggregate root or an Entity?


Solution

  • PhoneNumber is already unique, so Id is unnecessary.

    Phone number assignments change; so you'll want to think through the implications of that on your design (your conclusion might be "we'll make manual corrections to the data in that case").

    For the most part, the arguments about "natural keys" vs "surrogate keys" still hold.

    Are there any flaws if I use non-UUID Id in an Aggregate root or an Entity?

    UUID are not required; you can use integers under the right conditions.

    One property that can be useful is that all of the objects in your system have the same size key; your "identifier" logic is general purpose, you can report things about identifiers without needing to know in advance what kind of thing is being identified. Using UUID gives you that.

    Another interesting property of UUID is that we have standard ways of computing UUID from data (see "Named UUID"); so you might take some business data - like a phone number - generate the corresponding UUID, then use that as the identifier (which gives you sameness - UUID for everything - but does not solve the "what if the phone number changes?" question).