Hexagonal Architecture for Java

1. Overview

Hexagonal Architecture is a style which talks about layering your objects in such a way that isolates your core logic from outside elements. Core logic is the piece specific to your business and outside elements are like integration points  e.g DBs, external APIs, UIs and others. It divides software into inside and outside parts. Inside part contains Core Business logic and Domain layer (explained in Layered Architecture). Outside part consists UI, database, messaging and other stuff. Inside and Outside part communicate with each other via ports and adapters.

2. Benefits

  • Software developed using this architecture is independent of the channels and can support multiple channels
  • Easy to swap out the inbound and outbound integration points
  • Testing of the software becomes easy because we can mock integration points easily

3. Implementation in Java

As explained above, Hexagonal architecture is more around ports and adapters. In Java, Interfacesimplement the ports and Implementation class works as adapters. So, we will take a simple example with Spring Boot application and see how this style can be applied on this app.
In this application, we have  the functionality to create/view Employee Details. Core Business logic is in EmployeeService and the domain is an Employee. So, these will be considered as inside parts.

So now, this application can expose this functionality via REST or Messaging. Hence, we have created   EmployeeControllerAdapter to expose REST endpoints, which implement EmployeeUIPort.

As part of business logic, EmployeeService also needs to call the DB which is again an integration point (outside part) so we have created EmployeeRepositoryPort and EmployeeServiceAdapter implements this port.

So, we do see how EmployeeService has used the EmployeeUIPort port to expose its service and EmployeeRepositoryPort to interact with the DB. Also, EmployeeControllerAdapter and EmployeeServiceAdapter helps to integrate with REST APIs and DB.

4. Summary

To summarize it, Hexagonal Architecture is an approach to divide the application into inside and outside part. They are connected through port (exposed by inside) and adapters (implemented by outside). So, by applying this approach, the core use case code remains intact and can serve to multiple channels supporting different protocols. It also helps to make application tested easily. However, I would suggest  not to implement this architecture fully for whole application, but use interfaces and adapters selectively.

As always, the code of all examples above can be found over on GitHub.

No comments: