What is the right structure? for Hexagonal Architecture
How developers can break it and solutions to fix it.
Hexagonal architecture / CLEAN / Domain Driven Design knowledge is essential to understand the article.
For a detail explanation of hexagonal architecture, you can refer to https://medium.com/ssense-tech/hexagonal-architecture-there-are-always-two-sides-to-every-story-bc0780ed7d9c
Below is a common example of how developers usually structure projects according to hexagonal architecture and source material from internet.
The Problem:
Cross reference of classes!!! Because they would popup on Control + Space / Autosuggest in your IDE. :) for a single maven project structure.
How you can break it (innocently) 😇
- Imagine your DTO bean being used as an object to send json response or even worst your entity bean is being used to create json response.
- Your controller directly calling infrastructure (a database repository).
And if you do not have review mechanism in place, chances are that now you break the hexagonal architecture and are not aware until dooms day (example, where you were to break them into microservices) 😦
Solution: Multi-module Maven to the rescue!!!
Heard about multi-module maven project? It looks something like this;
Each module has their own dependencies and/or common dependencies and/or module dependencies would be shared across the main pom.xml of the application.
And an example of simpler applications
How this can restrict developers from making mistake;
- application* will have dependencies from domain-dto, domain-ports-api and commons
- domain will have dependencies from domain-dto, domain-ports-api , domain-ports-spi and commons
- infrastructure will have dependencies from commons and domain-ports-spi
- orchestration will have dependencies from all modules
You can refer to an example structure used in my existing opensource project at https://github.com/godwinpinto/authable (directory: authable-core-api)
Conclusion:
If your project is small(20–50 classes), then have proper reviews in place so to verify that no one breaks the structure(not multi-maven) else go with a multi-module maven project to clearly segregate the layers.
By layers it means in future;
- Different teams to manage different modules / components
- Large code base in future
- Easily portable based on your clients infrastructure (meaning different db vendors, caching mechanisms, etc.)
- For quicker porting time to microservices from monolith.
Thanks for reading.