Remember the term cohesion from one of the previous articles? Modules in DDD realm play by this rule, meaning to keep connected things next to each other. The best way to achieve a perfect Module structure, is to group classes by the processes they are part of and by Aggregates. Since a picture is worth more than a thousand words, let me show you some code.
Modularizing Cart And Order
We have to start with some directory structure. The general idea is to use the following schema:
Domain/Bounded Context/Layer/Aggregate
what translates to:
sales/online_store/domain/cart
sales/online_store/domain/order
Files and directories listing will look similar to this:
As you have noticed, there is something called a Layer within our path. It comes from the concept that every Bounded Context is build with four Layers: domain, infrastructure, application and ui. It comes from so-called layered architecture where every layer serves its special purpose:
- domain - involves all Tactical building blocks, business rules and interfaces for data providers, not aware of other layers
- infrastructure - layer where all concrete implementations of data providers reside like Repositories, not aware of remaining layers
- application - is aware of domain and infrastructure layers, uses them during particular process orchestration
- ui - may be HTTP controller, CLI command or any other kind of user interface, responsible for running application services, is aware of all the layers
Can you see how clean and well-organised our code is? Every Aggregate has its own Module, all Entities and ValueObjects are kept close to each other. There is no need to browse many directories in order to collect information about building blocks used. Every Aggregate may communicate with others using Domain Events what helps us to keep a loose coupling between them.
Summary
From now on, our code will be highly cohesive and loosely coupled thanks to the neat Module structure. More on layers and proper architecture in upcoming articles. Stay tuned and see you there.