What is the right structure? for Hexagonal Architecture

Godwin Pinto
3 min readApr 26, 2023

--

How developers can break it and solutions to fix it.

Hexagonal Architecture Image source

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.

Hexagonal structure

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) 😇

  1. 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.
  2. 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;

Multi-module maven project structure

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.

Complex systems - hexagonal architecture

And an example of simpler applications

Relatively simpler systems — hexagonal architecture

How this can restrict developers from making mistake;

  1. application* will have dependencies from domain-dto, domain-ports-api and commons
  2. domain will have dependencies from domain-dto, domain-ports-api , domain-ports-spi and commons
  3. infrastructure will have dependencies from commons and domain-ports-spi
  4. 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;

  1. Different teams to manage different modules / components
  2. Large code base in future
  3. Easily portable based on your clients infrastructure (meaning different db vendors, caching mechanisms, etc.)
  4. For quicker porting time to microservices from monolith.

Thanks for reading.

--

--

Godwin Pinto
Godwin Pinto

Written by Godwin Pinto

Principal engineer by profession | Business software application ideation and development enthusiast

Responses (3)