mogronalol mogronalol - 1 year ago 59
Java Question

Can you reference other aggregates in a factory when implementing domain driven design?

I have two aggregates,

. An
stores a reference to the
via it's

If I want to create an employee, I need to provide it with the company ID:

new Employee(name, companyId)

What I can't get my head around is how to get the
of the
if the client provides only the company name. In other words, I see this happening:

Employee buildEmployee(String name, String companyName) {
Company company = companyRepository.findByName()
return new Employeee(name, company.getGUID())

Something feels wrong to me, as now I've introduced a dependency on the
aggregate in order to create an
. Even worse would be that if these were two were separate microservices, as I'd have to make a rest call to get the company name.

Is there a way to avoid this coupling, or are my entities modelled incorrectly?

Answer Source

What your model currently expresses is

Every employee works for exactly one Company.

With that, it's absolutely clear that there must be a Company before you can create an Employee.

I see two different solutions that could fit here:

  • Pass the Company into buildEmployee. This communicates the fact creating an Employee requires a Company best.

  • Pass in the GUID of the company. This may be suitable for cases where you already have this information, but you don't have the whole Company object available (e.g. creating a co-worker for an existing employee).

No matter which approach you take, you should avoid loading data through a repository from within the factory. It's better to leave this for the calling app service, because the app service might require the Company anyway (e.g. to do some kind of input validation).

Keeping all repository interaction in the app service will make your application more robust and easier to reason about. After all, repository access usually involves network interaction and delay.

So to sum up, there's nothing wrong with having a dependency on Company from buildEmployee, but you should avoid calling the repository.

If depending on Company still feels wrong, then you should reconsider your model.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download