Is there a universally right structure? A look at hexagonal architecture

How developers can innocently break it and solutions to fix it.

ยท

2 min read

Is there a universally right structure? A look at 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. (They all are tailored in some way, but mean the same)


For a detailed explanation of a hexagonal architecture, you can refer link

Below is a common example of how developers usually structure projects according to hexagonal architecture and source material from the internet.

Hexagonal structure

The Problem:

Cross-reference of classes!!! Because they would pop up 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 is directly calling the infrastructure (a database repository).

And if you do not have a review mechanism in place, chances are that now you break the hexagonal architecture and are not aware until dooms day (As an example, where you were to break them into microservices) ๐Ÿ˜ฆ

Solution: Multi-module Maven to the rescue!!!

Heard about the multi-module maven project? It looks something like this;

Multi-module maven project structure

Each module has its 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 mistakes;

  1. application* will have dependencies from domain-dto, domain-ports-api and commons

  2. the 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 (guestimates of 20โ€“50 java files), then have proper reviews in place to verify that no one breaks the structure(not multi-maven) else go with a multi-module maven project to 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 client's infrastructure (meaning different db vendors, caching mechanisms, etc.)

  4. For quicker porting time to microservices from the monolith.

Thanks for reading.

ย