Hexagonal Architecture in Java
Join the DZone community and get the full member experience.
Join For FreeOverview
Hexagonal Architecture is a software architecture that allows an application to be equally driven by users, programs, automated tests, or batch scripts and to be developed in isolation from its run-time target system. The intent is to create an application to work without either a User Interface or a database so that we can run an automated regression test against the application, work with an application when a run-time system, such as a database is not available, or integrate applications without user interface.
Motivation
Many applications have two ends: a user-side and server-side, often designed in two, three, or n-layers architecture. The main problem with n-layered architecture is the layer lines are not taken seriously, causing application logic to leaks across the boundaries. This entanglement between the business logic and the interaction makes it impossible or difficult to extend or maintain the application.
For instance, adding a new attractive UI to support new devices could be a tough task when the application business logic is not completely isolated in its own boundary. In addition, applications can have more than two sides that make it more difficult to fit well in one-dimensional layer architecture, as shown below.
The hexagonal, or ports and adapters or onion architecture, solves these problems. In this architecture, the application in the inside communications over some number of ports with systems on the outside. Here, the term hexagonal itself is not important, rather it demonstrates the effect to insert ports and adapters as needed in the application in a uniform and symmetric way. The main idea is to isolate the application domain by using ports and adapters.
Organizing Code Around Ports and Adapters
Let's build a small anagram application to show how to organize code around ports and adapters to represents the interaction between inside and outside the application. On the left, we have an application, such as console or REST and inside is the core business logic or domain. The anagram service takes two Strings and returns a Boolean corresponding to whether or not the two String arguments are anagrams of each other. On the right, we have the server-side or infrastructure, for instance, a database for logging metrics about service usage.
The Anagram application source code below shows how the core domain is isolated inside and ports and adapters are provided to interact with it.
Domain Layer
The domain layer represents the inside of the application and provides ports to interact with application use cases.
IAnagramServicePort
interface defines a single method that takes two String words and returns a boolean.AnagramService
implements theIAnagramServicePort
interface and provides business logic to determine whether or not the two String arguments are anagram. It also uses theIAnagramMetricPort
to output the service usage metric to server-side run-time outside entities such as a database.
Application Layer
The application layer provides different adapters for outside entities to interact with the domain. The interaction dependency goes inside.
ConsoleAnagramAdaptor
uses theIAnagramServicePort
to interact with the domain inside the application.AnagramsController
also uses theIAnagramServicePort
to interact with the domain. Similarly, we can write many more adaptors to allow various outside entities to interact with the application domain.
Infrastructure Layer
Provide adapters and server-side logic to interact with the application from the right side. Server-side entities, such as a database or other run-time devices, use these adapters to interact with the domain. Note the interaction dependency goes inside.
Outside Entities Interacting With the Application
The following two outside entities use adapters to interact with the application domain. As we can see, the application domain is completely isolated and equally driven by them regardless of external technology.
Here's a simple console application interacting with the application domain using an adapter:
x
public class AnagramConsoleApplication {
private ConsoleAnagramAdapter anagramAdapter;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String word1 = scanner.next();
String word2 = scanner.next();
boolean isAnagram = anagramAdapter.isAnagram(word1, word2);
if (isAnagram) {
System.out.println("Words are anagram.");
} else {
System.out.println("Words are not anagram.");
}
}
}
Here's an example of a simple test script mocking the user interaction with the application domain using a REST adapter.
x
public class AnagramsControllerTest {
private static final String URL_PREFIX = "/anagrams/";
private MockMvc mockMvc;
public void whenWordsAreAnagrams_thenIsOK() throws Exception {
String url = URL_PREFIX + "/Hello/hello";
this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("{\"areAnagrams\":true}")));
}
public void whenWordsAreNotAnagrams_thenIsOK() throws Exception {
String url = URL_PREFIX + "/HelloDAD/HelloMOM";
this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("{\"areAnagrams\":false}")));
}
public void whenFirstPathVariableConstraintViolation_thenBadRequest() throws Exception {
String url = URL_PREFIX + "/11/string";
this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isBadRequest()).andExpect(
content().string(containsString("string1")));
}
public void whenSecondPathVariableConstraintViolation_thenBadRequest() throws Exception {
String url = URL_PREFIX + "/string/11";
this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isBadRequest()).andExpect(
content().string(containsString("string2")));
}
}
Conclusion
Using ports and adapters, the application domain is isolated at the inner hexagon, and it can be equally driven by a user or automated test scripts regardless of the external system or technology.
Opinions expressed by DZone contributors are their own.
Comments