Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Hello, Hexagonal Architecture

DZone's Guide to

Hello, Hexagonal Architecture

An explanation of what hexagonal architecture is, why it's useful, and an outline of the design with code snippets.

· Java Zone
Free Resource

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

When developing software we're always craving for architecture, because we want our software be easily changed in the future. 

So, architecture stepped in for maintainability. Here maintainability means how easily we can incorporate changes without disturbing the old code.

Every added feature in software comes with a risk: risk of breaking the program, maintainability, rigidity, dependencies, etc, There are many shades of risks we call technical debt.

Technical debt has an inverse relationship with maintainability, using architectural styles we want to decrease the risk, or I should say make it consistent when adding new features.

We experienced that when we started writing code it was easy to add features, and gradually it becomes harder to do so unless we use the proper architecture for that project.

Hexagonal Architecture

In one sentence, Hexagonal Architecture says: The core business logic talks to other parts of the application through a contract.

Your software development logic should talk to other pieces, meaning the database, any JMS Queues, any Flat files, HTTP requests, FTP, etc through a contract or an interface in Java.

The benefits of this type of design is whatever the input or output, every channel has to implement the same contract/interface to talk with our software. So from our perspective all chanells are the same, as all implement the same contract so our software can deal with any types of inputs and outputs.

Benefits

  1. Easily incorporates any channels like Flat file, RDBMS, NoSQL, Http, Ftp, JMS, etc.

  2. Our software can be easily tested because it is easy to create a mock when there is a need to implement the contracts.

  3. Adding new requirements means adding plugins or implementing the contracts.

  4. Proper separation of concern.

  5. Maintains IOC as higher level and lower level talking through contract.

Sometimes we called Hexagonal architecture Port and Adapter or Onion architecture. With these styles we have a port for each channel, such as a database.

The tasks we have to perform are:

  1. To implement the contract to talk with our software. As database APIs say JDBC is itself a contract, or Hibernate is itself a framework, we need to create a GOF adapter pattern where we can implement a strategy which converts JDBC-related operations to our contract-related operations.

  2. Plug this adapter into our port to talk with this channel.

Outline of the Design

Software Contract

package com.example.architecture.hexagonal;
public interface IPersists<T,TCOMMAND> {
   public void save(T t,TCOMMAND commandObject);
   public void delete(T t,TCOMMAND commandObject);
}

This is the general contract for talking with our software. Any output channel should implement that contract.

Here I take an example of how it can talk to a JPA entity which saves that data in the database.

DataBaseChannelAdapter.java

package com.example.architecture.hexagonal;
public class DataBaseChannelAdapter implements IPersists<EmployeeDomainObject,EmployeeCommand>{
   public void save(EmployeeDomainObject t, EmployeeCommand commandObject) { 
       String underLyingJPAEntity = commandObject.getEntityClass();
       System.out.println("call save on " + underLyingJPAEntity);   
   }
   public void delete(EmployeeDomainObject t, EmployeeCommand commandObject) {
       String underLyingJPAEntity = commandObject.getEntityClass();
       System.out.println("call delete on " + underLyingJPAEntity);   
   }
}

As JPA Entity uses some JPA related annotation, I did not include this JPA entity as part of our Domain. I used JPA framework as an Outside Channel of our software domain, and DataBaseChannelAdapter takes our core domain Employee Object and takes a Command Object, which tells the adapter which JPA entity to call.

EmployeeDomainObject

package com.example.architecture.hexagonal;
public class EmployeeDomainObject {
   public String name;
   public String address;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getAddress() {
      return address;
   }
   public void setAddress(String address) {
      this.address = address;
   }
   @Override
  public String toString() {
      return "EmployeeDomainObject [name=" + name + ", address=" + address
              + "]";
   }
}

Our core Domain Employee Object does not depend on any framework, so I can plug any framework into it through an adapter. For example, I can easily change DatabaseAdapter to FileAdepter to save our core domain object in File.

EmployeeCommand.java

package com.example.architecture.hexagonal;
public class EmployeeCommand{
   public String entityClass;
   public String getEntityClass() {
      return entityClass;
   }
   public void setEntityClass(String entityClass) {
      this.entityClass = entityClass;
   }
   @Override
   public String toString() {
      return "EmployeeCommand [entityClass=" + entityClass + "]";
   }
}

This Command object helps an adapter to convert a Core Domain Object to an Underlying Output channel (database or file).

EmployeeDomainDao.java

package com.example.architecture.hexagonal;
public class EmployeeDomainDao<T,TCommand>{ 
   IPersists<T,TCommand> adapter;
   public void save(T t,TCommand commandObject)   {
      adapter.save(t, commandObject);
   }
   public void delete(T t,TCommand commandObject)   {
      adapter.delete(t, commandObject);
   }
   public IPersists<T, TCommand> getAdapter() {
      return adapter;
   }
   public void setAdapter(IPersists<T, TCommand> adapter) {
      this.adapter = adapter;
   }
}

This is our Core Domain Persist layer. Based on the adapter, it will call the exact output channel and persist our Domain Object.

Time to Test Our Software Design

Main.java

package com.example.architecture.hexagonal;
public class Main {
   public static void main(String[] args) {
     EmployeeDomainDao<EmployeeDomainObject,EmployeeCommand> dao = new EmployeeDomainDao<EmployeeDomainObject,EmployeeCommand>();
      IPersists<EmployeeDomainObject,EmployeeCommand> adapter= new DataBaseChannelAdapter();
      dao.setAdapter(adapter);
      EmployeeDomainObject emp = new EmployeeDomainObject();
      emp.setName("Shamik Mitra");
      emp.setAddress("India,Kolkata");    
      EmployeeCommand command = new EmployeeCommand();
     command.setEntityClass("com.employeemanagement.entity.EmployeeJpaEntity");
      dao.save(emp, command);
      dao.delete(emp, command);
   }
}

Output

Hexagonal Layers 

Object StateEmployeeDomainObject [name=Shamik Mitra, address=India,Kolkata]
call save on com.employeemanagement.entity.EmployeeJpaEntity
Object StateEmployeeDomainObject [name=Shamik Mitra, address=India,Kolkata]
call delete on com.employeemanagement.entity.EmployeeJpaEntity


Picture courtesy Google

Application Domain: As I said earlier it is the software where all software related business logic and validation goes on. This is the module that every outside module talks with through a contract.

Application/Mediation Layer: Kind of like a services layer, it adopts the framework layer or an outside layer and makes necessary changes according to the domain layer contract to talk with the domain layer, or in the same way return back the result from the domain to the framework layer. It sits between the domain and framework layer.

Framework Layer: This layer as for input/output channels, a.k.a. the outside world, and uses an adapter to adapt the data and transform it according to our software contract.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
hexagonal architecture ,java ,architecture ,messaging

Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}