Hexagonal Architecture: the practical guide for a clean architecture

Did you ever face problems when comes the time to upgrade the stack of your software? Are you able to distinguish your functional tests from your integration ones? Migrating your legacy means rewriting everything from scratch?
Discover how the Hexagonal Architecture, a clean architecture pattern also known as Ports and Adapters, can help!


Business logic overboard!


In a previous experience, my team had to port an old application on a brand-new stack. The software was moving from an EAR/SQL app to a self-contained JAR using NoSQL. By studying it, we quickly realized that we had to redo the entire infrastructure. In fact, the only thing that didn’t have to change was the business logic. So, it makes sense to reuse it, right?

a classic layered architecture implementation
a classic layered architecture implementation

After a deeper look, the maven module named model was POJOs with only getters and setters, totally anemic… Although there is also service module, the business logic is shared across all the layers. It was drowned in a lot of technical code such as DAOs creation, Serialization, etc. There were no ways to extract the business logic! Some parts of it were relying on the technical behavior of the old framework we tried to remove. And why? Because there was no clean separation between the business logic and the technical code.

Separation of concerns: isolating the business logic

Picture of Rakicevic Nenad


The Hexagonal Architecture created by Alistair Cockburn ensures the re-usability of the business logic by making it technical-agnostic. So, changing the stack will have no impact on the domain code.

One key concept of this architecture is to put all the business logic into a single place named the Domain. Let’s update the previous schema:

overview of a layered architecture
overview of a layered architecture

Important constraint: the domain depends on nothing but itself; this is the only way to ensure that the business logic is decoupled from the technical layers. How do we achieve that on the previous schema? The domain clearly depends on the persistence layer! Well, by using a pattern you may know: the inversion of control. By calling the domain the Hexagon, it will look like this:

Overview of a Hexagonal Architecture
Overview of a Hexagonal Architecture

The inversion of control was pretty magic, let’s see later how it works. Now you got an overview of what is the Hexagonal Architecture:

  • Only two worlds, inside and outside the Hexagon. Inside: all the business logic, Outside: the infrastructure – meaning all your technical code.
  • The dependencies always go from outside toward the inside of the Hexagon. It ensures the isolation of the business domain from the technical part.
  • One corollary of this is the Hexagon depends on nothing but itself. And not only regarding your own layers: It must not depend on any technical framework. That includes external annotations like Jackson or JPA.

No frameworks allowed in the domain (almost)

Picture of Drew Rae


Let me explain you a bit more the last point, which is a really important one. In another experience, my team had to port an application from the “classic” Spring framework to Spring Boot. The main (painful) problem we had: leveraging too much on the Spring Integration Tests to validate our functionalities. Furthermore, those functionalities were also too coupled with Spring.

At the first try of our Spring Boot migration, all functional tests were failing. We were not able to determine if the business logic was broken somewhere or if the reason was purely technical. We eventually figured out that it was an integration problem at test level. So we fixed all the tests one by one by crossing our fingers… Hoping the domain was still correct.

No framework used in the Hexagon means the business domain can be reused regardless the change of the technical stack. It will as well increase the testability of your domain since you no longer mix it with integration issues. And at the end, you’ll do real functional tests thanks to this constraint of the Hexagonal Architecture. This way the functional tests will directly interact with the Hexagon and only with it.

NOTE: In Maven, you can ensure this constraint using the enforcer plugin.

The Hexagonal Architecture Inversion of Control

Picture of Matheus Bertelli 


Remember the inversion of control? To ensure the isolation of the Hexagon, the dependencies on downstream layers have been inverted. The trick is in fact pretty simple as you can see:

Implementation of the Hexagonal Architecture
Implementation of the Hexagonal Architecture

The outside of the Hexagon (the infrastructure) is divided in two virtual parts, the left side and the right side. On the left, you got everything that will query the domain (the controller, the REST layer, etc.). And on the right, everything that will provide some information/services to the domain (persistence layer, third party services, etc.).

Protecting the domain with an anti-corruption layer


To let the outside to interact with the domain, the Hexagon provides business interfaces divided in two categories:

  • The API gathers all the interfaces for everything that needs to query the domain. Those interfaces are implemented by the Hexagon.
  • The SPI (Service Provider Interface) gathers all the interfaces required by the domain to retrieve information from third parties. Those interfaces are defined in the Hexagon and implemented by the right side of the infrastructure. We will see that on some circumstances, the Hexagon can also implement the SPI.

There are two important facts here:

  • The API and the SPI are parts of the Hexagon.
  • The API and the SPI only manipulate domain objects of the Hexagon. It indeed ensures the isolation.

In a layered architecture, the Business Object or the service usually creates the DAOs. In the Hexagonal Architecture, the domain only handles domain objects. Consequently, the persistence is in charge to translate the domain objects into any “DAOs” to be persisted. This is what we call an adaptation.

The modularity strength of the Hexagonal Architecture


As mentioned above, the Ports and Adapters architecture is another name of the Hexagonal Architecture. It comes from the power of the modularity of this architecture. Because everything is decoupled, you can have a REST and JMS layers in front of your domain at the same time without having any impacts on it.

Adapters modularity in Hexagonal Architecture
Adapters modularity in Hexagonal Architecture

On the SPI side, you can change from a MongoDB driver implementation to Cassandra if needed. Since the SPI won’t change because you change the persistence module, the rest of your software won’t be impacted. The API and the SPI are the Ports and the infrastructure modules using or implementing them are the adapters.

How to implement the Hexagonal Architecture?


One more rule here: always start with the inside of the Hexagon. This will bring you a lot of advantages:

  • Focus on the feature instead of the technical details. Because only the feature brings value to your company. A developer working on another business domain is able to put in place a Spring Controller. But the double declining balance method will sound like Wookiee for him unless he worked for an accountancy company.
  • Delay choices on technical implementation. Sometimes it’s really hard to know which technical implementation you really need at the beginning. Consequently, delaying this choice helps you to focus on what brings the primary values to your company – the feature. Furthermore, after the implementation of the business logic, some new elements can help you to make the best choice regarding your infrastructure. You can discover that the domain is more relational than expected, so SQL is a good choice for your database.
  • One corollary is it ensures the Hexagon is a stand-alone. Since you should never write code without tests, it means that the Hexagon is self-tested. Furthermore, we got here real functional tests focusing on the business only.

A detailed implementation of the Hexagonal Architecture is covered in the following article

A Test-Driven implementation


With the Hexagonal Architecture, you put your functional tests in your domain. Those tests will call directly the domain API while avoiding any disturbance from the technical part. In a way you are creating an adapter simulating the Controller to test the features of the domain.

Starting with the functional tests of the Domain

My advice is writing your functional scenario first using the Behavior-Driven Development to describe your feature.

Check out those articles to learn more about Behavior-Driven Development (BDD) and How to implement a Functional Test.

The first step of the “double-loop” will produce your functional test using ATDD. And write the API interface which will be the entry point of your feature. Then implement your tests with TDD and finally implement your business logic. While writing it, you might need to retrieve some data from the database for example, so create an SPI. Since the right side is not yet implemented, create a stubbed implementation of this SPI inside your Hexagon. That can be achieved using an in-memory database implemented with a Map.

Functional Tests in Hexagonal Architecture
Functional Tests in Hexagonal Architecture

You can choose to keep the Stubs in the test scope of your application. But you can as well temporarily ship it if needed. For example, once we made the first feature on the Hexagon, we stubbed an external service and the database. Because our client needed us to provide an interface contract, we secondly exported the domain through a REST controller. So we shipped a first version with stubbed data on the right side of the infrastructure. This way, the client was able to see the structure of our data and the expected behavior of the feature. It was much more reliable than creating by hand some JSON samples of our requests and responses because it actually deals with real business constraints.

Finishing with the adapters

The next step is usually opening the left side first. This way you can put in place some integration tests on the feature. At this time you can provide some live documentation and ensure an interface contract with your clients.

Hexagonal Architecture integration test of a left adapter
Hexagonal Architecture integration test of a left adapter

Finally, open on the right by implementing the SPI of your feature by taking advantage of the integration tests. I strongly recommend your tests to be stand-alone to avoid any instability during build time. You should always mock your third parties using something like Wiremock for external services or Fongo to simulate a MongoDB.

Hexagonal Architecture end-to-end integration test
Hexagonal Architecture end-to-end integration test

Loop the same way for your other features.

Architecture Hexagonale Level 2 : Comment bien écrire ses tests ? by Julien Topçu & Jordan Nourry

For more information, an Hexagonal Architecture Testing Strategy is available on GitLab which is also described in the talk above 🇫🇷.

Hexagonal Architecture in a nutshell

Picture of Alex Andrews 


So, now we have seen what is Hexagonal Architecture! There is a real benefit in decoupling the business logic from the technical code. It ensures your business domain is durable and robust regarding the continuous evolution of the technology.

The Hexagonal Architecture offers you a real means to achieve this by:

  • Putting all the business logic in a single place.
  • The domain is isolated and agnostic regarding the technical part because it depends on nothing but itself. That’s why the dependencies always go from outside to the inside of the Hexagon.
  • The Hexagon is a stand-alone module. Thus, It increases the testability of your domain by writing real functional tests which don’t have to deal with technical issues.
  • This architecture offers a powerful modularity. It helps you to write as many adapters as needed with a low impact on the rest of the software. And since the domain is agnostic from the stack, the stack can be changed without any impact on the business.
  • By always starting with the domain, you ensure to bring value to your customer by focusing on the feature development. This way you can delay choices on technical implementation to make the best choice at the right time.

Some feedbacks

Hexagonal Architecture is not suitable for all situations. Like Domain-Driven Design, this is really applicable if you got a real business domain. For an application which transform a data to another format, that’s might be overkill.

To finish on this, always be pragmatic when you adopt a new technology. As stated before, the Hexagon must not depend on any technical framework, but exceptionally you can. For example, in our case the Hexagon had three exceptions: Apache Commons Lang3 (StringUtils), SLF4J and the JSR305 of Findbugs. Because we didn’t want to create the wheel since those frameworks had very low impacts on the domain. One good side effect of the Hexagonal Architecture, is that you keep challenging yourself before integrating a new framework. By using this architecture, we reduced the number of dependencies from fifty to only three or four for the domain. And this is very good from a security perspective.

27 Comments Add yours

  1. Juan says:

    Excellent article! It’s one of the best I’ve read about this subject. Congratulations. I do apply ports&adapters architecture in my projects too.

    1. Thank you Juan

  2. A very nice write up indeed, especially the division between API/Domain/SPI.

    But I wonder whether it’s ok to expose my domain objects – which should provide rich business functionality – in the interface that’s inside the API? This would mean that the controller could invoke those business methods directly on the Entities it sees, without going through the API at all.

    So, should the API really use the domain objects directly or should it provide some DTOs, which will be mapped to domain objects in the implementation of those API interfaces?

    1. Hi Peter, thank you for your comment.

      API and SPI are interfaces uses to enter or step outside a domain. So usually those interfaces only uses domain objects. DTOs are usually used to transfer data over the network and are most of the time POJOs. With the Hexagonal Architecture philosophy, people generally uses DDD where POJOs are not recommended inside the domain.

      One of the main reason of that is, every domain objects have to be valid when they enter the domain. In DDD – thourgh the object oriented paradigm – this is ensured by the constructors of your domain objects.

      Another way to answer to you, in HexArch, everything inside the Hexagon is a part of the domain (business) and not technical. If the API is using DTOs, it would mean those DTOs are part of your domain objects, which doesn’t really make sense to me since they are dedicated to technically represent a domain object.

      Hope I was enough clear 🙂

      1. Juan says:

        Hello J’aime, I had the same question than Peter.
        I use HexArch with DDD. The inner of the hexagon isn’t just the domain, but the application layer too. The application layer and the domain model would be both inside the hexagon. The API of the hexagon would be the application layer of DDD. So putting DTOs there it would be ok. The Domain model is inner. The application layer would map DTOs to/from rich domain objects. Well that’s my approach, but I think that it is correct, because domain objects shouldn’t been exposed to adapters (infraestructure). The point is that the inside of the hexagon is layered into application and domain (application surrounding domain). Also, mapping would be made on the right side (persistence port), for translating domain model and persistence model.
        Regards,
        Juan.

      2. Hi Juan,
        In fact from what I saw with applications implementing Hexagonal Architecture, we get rid off the application layer which becomes a bit redundant.
        The main purpose of exposing your domain objects to the infrastructure, is to ensure the inversion of control. The other reason, you ensure this way to fail fast. So when your adapter is attempting to create an incorrect domain object, it will fail in the infrastructure.
        It doesn’t mean there is no reason to keep an application layer in the domain, as long as you can take advantage of it. Be careful to avoid any confusion with an application infrastructure layer (specially if you are using springboot).
        The only possible caveat I can see with that solution, is that you’ll have two representations of your domain concepts inside the domain, if I understood well what you did. One will be the real domain object and the second one the DTO.
        Thanks again for your comment.

  3. Juan says:

    Hi, you are wellcome, thanks to you for answering and talk about this subject. As I said before, your article is one of the best I’ve seen about hexagonal architecture. I like it. Some comments about what you said and what I think:

    ——————————————————–
    (1) “we get rid off the application layer which becomes a bit redundant”

    In my opinion you shouldn’t get rid of the application layer, it is not redundant, it should exist regardless of the achitecture pattern you use. It is the use case boundary and orchestrates domain objects. It cares about cross-cutting concerns like transactions. It is the direct client of domain model, and it isolates the domain from the outside world, keeping the domain impolute. It fits like a glove as the primary port (API of the hexagon) of hexagonal architecture. This architecture pattern says nothing about the structure inside the hexagon, it can be whatever you want. Alistair Cockburn uses to name the hexagon as the “App” (you can watch his “Alistair in the Hexagone” videos).

    ——————————————————–
    (2) “The main purpose of exposing your domain objects to the infrastructure, is to ensure the inversion of control”

    You can apply inverion control without exposing domain objects. You could expose just interfaces of the domain objects (representing just the state, not the behaviour).

    ——————————————————–
    (3) “Be careful to avoid any confusion with an application infrastructure layer (specially if you are using springboot)”

    I know. A Spring Boot application belongs to infraestructure. It is a primary adapter (MVC, REST API, CLI, TEST o whatever). It calls the primary port of the hexagon (API of the hexagon).

    ——————————————————–
    (4) “The only possible caveat I can see with that solution, is that you’ll have two representations of your domain concepts inside the domain, if I understood well what you did. One will be the real domain object and the second one the DTO”

    In the left side, there are DTOs belonging to the API port of the hexagon (the application service interface of DDD). These DTOs are not representations of domain concepts inside the domain, they collect plain data from the UI needed by a use case. The application layer maps from/to DTOs and domain objects.

    In the right side, there are “State Objects”. Unlike DTOs, according to Vaughn Vernon, this state objects do belong to the domain. They hold the state of “real” domain objects. The state is what the repositories persist.

    Regards,
    Juan.

  4. Juan says:

    Hi Julien. Thanks for adding a link to my article. Regards, Juan.

  5. Fernando Franzini says:

    Hello. I do not know the author’s name, but very good article, really is the best I could find until today. But it gave me many doubts. Could I post the doubts here to see can you clarify me? Best Regards

    1. Hello,

      Thanks for your feedback.
      Feel free to ask any questions here 🙂

      Regards,
      Julien

  6. If you need more information, you can now find a demo application here: https://gitlab.com/crafts-records/talkadvisor/talkadvisor-back

  7. Hi. Great article.
    I’m wondering about the next step.
    How would you organize the architecture when you have a very complex application that you would want it organized in modules?
    Would you consider each module as an hexagon? If so, it seems to me that you would end with dependency-hell again, now in the SPI, no?

  8. hugoquintela says:

    Hi. Great article.
    I’m thinking now of the next step.
    How would you organize the architecture of a complex app where you would want to have it organized in modules?
    Treat each module as an hexagon? If so, wouldn’t that result in “dependency-hell” neverthess, now between the SPI of each of those modules?

  9. Nagesh Danturti says:

    Thanks for a good write-up. I read it twice, but I still don’t get why the “Hexagon” shape to showcase your point. I could imagine any other shape in between – even a simple rectangle could convey the same meaning or a circle for that matter, no? I don’t see the relevance to a Hexagon – did I miss something? My apologies if I sound rude (its not the intention). Thanks for your understanding.

    1. As mentioned by Alistair Cockburn “the hexagon is not a hexagon because the number six is important, but rather to allow the people doing the drawing to have room to insert ports and adapters as they need, not being constrained by a one-dimensional layered drawing. The term ‘’hexagonal architecture’’ comes from this visual effect.”

Leave a Reply