R – How to create this component from root in DDD

domain-driven-design

I have a question about how to solve the following scenario using DDD.

I have 2 entities Person and Email with one to many relationship. A person can have zero or more email address(es).

Person is an aggregate root of Email which is a component.

class Person{
    Set<Email> emails = new HashSet<Email>
}

Class Email {
    String value;
    Email(String value){
    }
}

I have 2 requirements in the system:

  1. User can send a request to add a new Email to person

  2. User can create a list of emails temporarily and may or may not add them to person.

Does having 3 methods make sense in DDD? Or is there a better way to do meet my requirements above.

  1. To create Email from party but not add it to the emails list (see createEmail() below).

  2. Having a seperate method just to add email to the list (see setEmail() below).

  3. A method to create email for a person and add it to the emails list (see addEmail() below).


public Class Person{

    Set<Email> emails = new HashSet<Email>
    public void addEmail(String value){
        Email email = createEmail(value);
        emails.add(email);
    }

    public Email createEmail(String value){
        return new Email(value);
    }

    public void setEmail(Email email){
        emails.add(email);
    }   
}

Best Answer

Personally, I would see it different:

I would only see 'Person' as being an entity. Email is a value type (component) and not an entity, since it has no identity.

Then, I would expose the eMail adresses of a person as a read-only collection of the Person entity.

public class Person
{
    public void AddEmail( Email mail ) {}
    public void AddEmail( string mailAddress) {}
    public void RemoveEmail( Email mail ){}
    public void RemoveEmail( string mailAddress ){}

    Email[]  GetEmailAdresses() {};
}

public struct Email
{
     public Email( string address ){}

     public string Address
     {
         get {return _address; }
     }
}
Related Topic