Identifiers of entities in multiple bounded contexts

Viewed 601

Let's say that I have two bounded contexts, Billing and Shipping.

In Billing Bounded Context I have this:

class Account {
    private $id;
    private $address;
    private $zipCode;
    private $city;
    private $postbox;
}

And in the Shipping Bounded Context i have this:

class Recipient {
    private $id;
    private $address;
    private $zipCode;
    private $city;
    private $doorCode;
}

So now, the 2 models, as we all know relate to another a User in some other bounded context.

Should the Account and Recipient share the same id and this id would come from User Model.

Do I have to add a field in these models called $userId in addition to accountId and recipientId?

2 Answers

From the DDD perspective, you should add a field userId to Account and Recipient.

The reason is that Recipient, Account and User are entities. It means they should have their own identity. Even if your User always has only one Account, it doesn't mean that User is Account, so they cannot share the same id.

Additionally, it could be better to have the possibility of having several accounts for one user from the very beginning. Let's say a user decides to remove his account. In this case, I guess you shouldn't remove his past orders, so you shouldn't remove a User itself. You should remove a user's Account only.

If in the future, the same user decides to create a new Account, you could literally create a new one and have an old inactivated account and a new active account in your database.

However, I can imagine a design when you decide to use the same Id for these entities for some reason, even though it doesn't fit well with DDD principles. But if you decide to do so, it's better to use a clear name for the id field. Instead of just:

class Account {
    private $id;
    private $address;
}

you'd better have:

class Account {
    private $userId; // if it's userId we should express it explicitly in the name
    private $address;
}

Yes, referencing the user id from the User context as some external id in your other contexts (here in the Account and Recipient entities) is a valid approach.

You can even think if using some custom value object class that represents the user reference in your other contexts. With that you have strong typing for the reference to the user rather than simply using a string.

Related