DDD Address Solution – How to Use Domain-Driven Design to Solve Common Address Situations?

domain-driven-designdomain-model

This is a simple example to show a situation that I find hard to solve with DDD.

Consider this:
– A property (e.g. a house) has an Address.
– An address can be complete or partial (country only; country and state; country, state and city).
– When a end-user is searching for properties, I need to display a list of all countries.
– When a country is selected, I need to retrieve all related states.
– When a state is selected, I need to retrieve all related cities.

This can be easily done using a data driven approach (querying against a relational model), but when I try to model this, thinking in Domain Driven Design, I'm failing.

I have this obvious constraints:

  • A city can't exist without a estate.
  • A estate can't exist without a country.

Conclusion – country is the aggregate root to enforce this constraints.

I'm supposing that address is another aggregate root. But address can only refer to an aggregate root, so how can I refer a partial address? Do I need to think in another root?
When I need to query for city, I need to bring the whole country aggregate root?
And what if I need to search for all cities available for a given string? I need to query for all countries and than transverse through relations?

In this situation, the most obvious solution for me is to have and aggregate root for city, state, country and address. But this is an anemic model.
But to avoid an anemic model, it looks like the only way to solve is having different models. One to insert new cities (using the country aggregate) and others to retrieve and associate those entities. But this smells bad.

I'ts very hard to find a sample that cover a situation like this.
Can someone give me some directions? I'ts fine to recommend a book, but I would love some direct insights.

I read a lot about DDD and I know most of the terms (aggregate, entities, services, associations, value-objects).

Best Answer

Object-oriented modeling, especially in context of DDD is all about behavior. You are talking about anemic model, but I'm having hard time figuring out what behavior would country/state/city have. Mostly, they are just holders of data.

There is also a conflict in your narrative. You are saying the user can get a country or state and based on this, get the data on lower hierarchy. You cannot do this if country and state don't have identity to be identified with, meaning they have to be entities.

In your case, I wouldn't mind creating each of those as an entity. You could also create a composite key for each. For example city key would be composed of {country_id, state_id, city_id}. You can also enforce this by only allowing to "add" new state through country and new city through state. They could create the "containing" part of the key while leaving the child ID to database engine.

Related Topic