DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models

Trending

  • Enforcing Architecture With ArchUnit in Java
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Hexagonal Architecture for Beginners

Hexagonal Architecture for Beginners

Want to learn more about the hexagonal architecture?

By 
Aleksandr Kirilenko user avatar
Aleksandr Kirilenko
·
Jun. 27, 19 · Presentation
Likes (5)
Comment
Save
Tweet
Share
16.1K Views

Join the DZone community and get the full member experience.

Join For Free

The hexagonal architecture is one more approach to create maintainable software solutions (and it can be one more way to shoot yourself in the foot). The main idea is to separate core logic (business logic and domain) from frameworks. Usually, the first part is called inside and the last one is called outside. Inside provides a port to communicate with it, and at the same time, outside provides the implementation of this port called the adapter. This is why this particular development style has another name — the ports and adapters architecture.

Advantages

  • Ability to support multiple channels
  • Flexibility in choice of channels
  • Easy testing of core logic by the mock outside part

Implementation

Speaking of this implementation style in Java, it is easy to imagine that the classic interface plays a role in the port. Therefore, the adapter (the outside part) is the implementation of the current interface. This concept will be shown in the following simple Spring Boot application that will simulate the work of some stock (add/get some orders). The core of our app consists of business logic (OrderService) and the domain part (Order):

@Service
public class OrderService {

    private static int MAJOR_UNIT_CUTOFF = 1000;

    @Autowired
    private OrderDao dao;

    public void create(int unitCount) {
        dao.save(unitCount);
    }

    public boolean isMajor(int id) {
        Order order = getById(orderId);
        return order.getUnitCount() > MAJOR_UNIT_CUTOFF;
    }

    public Order getById(int id) {
        return dao.get(id);
    }
}
@Entity
@Table(name = "order_table")
@Data
public class Order {

    @Id
    @GeneratedValue
    @Column
    private int id;

    @Column
    private int unitCount;
}


Of course, it is a far-fetched example, but I suppose it helps to understand the concept in a simple way. As I previously said, our inside part should offer a port to integrate with it. In this specific case, our port is  OrderDao:

public interface OrderDao {
    void save(int unitCount);
    Order get(int id);
}


In this way, all repositories (the outside part) implement this interface and can be integrated with our inside part. Let us consider a simple one (OrderDaoImpl):

@Service
public class OrderDaoImpl implements OrderDao {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    @Override
    public void save(int unitCount) {
        Order order = new Order();
        order.setUnitCount(unitCount);
        em.persist(order);
    }

    @Override
    public Order get(int id) {
        return em.find(Order.class, id);
    }
}


Thus, we have a typical example of a pair (port, adapter) = (OrderDao , OrderDaoImpl), which is a major concept of the hexagonal architecture.

Test

As was mentioned previously, a pleasing benefit of considering this architecture style is that it is easy to test the business logic of our software with mock integration points. You can see that "complex" business logic lays in the isMajor(int id) method of our OrderService. Let us mock OrderDao and test this logic.

@RunWith(SpringRunner.class)
@SpringBootTest
public class OrderServiceTest {

    @InjectMocks
    private OrderService service;

    @Mock
    private OrderDao dao;

    @Test
    public void whenUnitCountGreaterThenHundred_thenOrderIsMajor() {
        Order majorOrder = new Order();
        majorOrder.setUnitCount(1001);
        doReturn(majorOrder).when(dao).get(1);

        assertEquals(true, service.isMajor(1));
    }

    @Test
    public void whenUnitCountLessThenHundred_thenOrderIsNotMajor() {
        Order notMajorOrder = new Order();
        notMajorOrder.setUnitCount(1000);
        doReturn(notMajorOrder).when(dao).get(1);

        assertEquals(false, service.isMajor(1));
    }
}


Conclusion

The hexagonal architecture offers efficient tools (ports/adapters) to isolate the business logic of our application from outside elements. Additionally, it leads to flexibility in the testing of our app and enhances the number of possible integration points.

Example code from this post can be found over on GitHub.

Architecture

Opinions expressed by DZone contributors are their own.

Related

  • Event Driven Architecture (EDA) - Optimizer or Complicator
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • How to Build Real-Time BI Systems: Architecture, Code, and Best Practices
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!