When laying out your solution, it’s important to have a clear separation between your application and your domain. In most areas that I see, the application is either a Web API or a web application.
What does this actually mean?
Why you want to keep it this way
First rule of the SOLID principle, Single Responsiblity – one of the best ways of getting your code in a mess is mixing responsibilities.
Imagine if you had a shopping cart API, and you placed logic for adding to a basket (data reads/writes and all) directly in the Controller.
Some of the problems that come to mind when you do this:
1. Impossible to test the domain logic without having to test the API itself
2. Whenever you need to do a similar operation elsewhere, you’re duplicating your code
3. Less, because there’s no clear separation between what’s happening within your domain, and what’s simply being done to get your data to your users
Remember, your API isn’t your domain, it’s simply a form of transport for your domain.
Request and Responses
The request and responses to your API and your domain are likely to be similar, but more likely than not, not be the same.
Now, this isn’t always the case, you don’t always have to have a distinction between your domain request/response and your API request/response – but it’s important to realise the fact that they’re not always the same thing.
Why is this the case? Well, sometimes, your Domain objects/DTOs have extra things that are essential to achieve certain functionalities. As for your application response, the response may include more things than the associated domain object, or in some cases, even a composition of many different domain objects.
Your domain exceptions should be exceptional things that you don’t expect in your domain.
Application exceptions are more to do with getting requests to your domain, or authentication errors.
Authorisation can be a tricky one, this may or may not belong to the domain depending on multiple factors. This is more of a design decision than anything else.
Your Application should never ever access your data directly, EVER. Your Applications job is to pass the request to our domain and give the response back to the client.
Extra Notes On Microservices
DDD in Microservices become especially important, as leaking implementation can cause a lot more problems down the line. Always try to distinguish between your domain (the main reason your micro service exists), and your implementation of your domain.