· Architecture  · 2 min read

Foundations: Demystifying Hexagonal Architecture

Is your business logic polluted with framework code? Discover how Ports and Adapters can save your codebase from spaghetti coupling.

Is your business logic polluted with framework code? Discover how Ports and Adapters can save your codebase from spaghetti coupling.

Software frameworks like Spring Boot are powerful, but they have a dark side: if you’re not careful, your core business logic becomes inextricably “married” to the framework. Annotations everywhere, database dependencies in your entities, and controllers containing business rules.

Hexagonal Architecture (also known as Ports and Adapters) is the antidote.

The Core Concept: Inside vs. Outside

Imagine your application as a fortress.

  • The Inside (Domain): This is your pure business logic. User, Account, Transaction. It knows nothing about databases, APIs, or the web. It is pure Java (or whatever language you use).
  • The Outside (Infrastructure): This is the messy world of implementations. Postgres, REST Controllers, Kafka Listeners, Third-party APIs.

Ports and Adapters

How do they talk? Through strict contracts.

1. Ports (The Interfaces)

The Domain defines Ports. A Port is simply an Interface that says “I need to save a user” or “I can process a payment”.

  • Inbound Port: “I allow outside things to ask me to do work” (e.g., UserService).
  • Outbound Port: “I need to talk to the outside world to finish my job” (e.g., UserRepository).

2. Adapters (The Implementations)

The Infrastructure provides Adapters.

  • Inbound Adapter: A REST Controller that takes a JSON request, calls the UserService (Inbound Port), and returns a response.
  • Outbound Adapter: A JPA Repository that implements UserRepository (Outbound Port) and talks to Oracle.
graph LR
    subgraph Infrastructure [Outside World]
    Controller[REST Controller]
    DB[Postgres DB]
    end

    subgraph Adapters
    RestAdapter[Web Adapter]
    JPAAdapter[JPA Adapter]
    end

    subgraph Hexagon [The Domain]
    Direction((Core Logic))
    end
    
    Controller --> RestAdapter
    RestAdapter -->|Inbound Port| Direction
    Direction -->|Outbound Port| JPAAdapter
    JPAAdapter --> DB

Why Bother?

  1. Testability: You can test your entire business logic without spinning up a database or a web server. Just mock the Ports.
  2. Flexibility: Want to switch from MySQL to MongoDB? Just write a new MongoAdapter that implements the UserRepository interface. The Domain code doesn’t change a single line.
  3. Focus: Developers focus on what the application does (Domain), not how it stores data (Infrastructure).

Hexagonal Architecture is the standard for building long-lived, maintainable enterprise systems. It effectively separates the essential complexity of your business from the accidental complexity of your tools.

Back to Blog

Related Posts

View All Posts »