Chapter 5: Hexagonal Architecture: Protecting the Core: The Power of Ports and Adapters
This chapter introduction previews decoupling business logic from external systems and the vocabulary, diagram, code, and origins of hexagonal architecture.
After this chapter you will be able to
- Database Anchor in Layered Systems. Explain why a well-layered application can still depend heavily on its database, making it difficult to test or run business logic without infrastructure.
- Protected Core Organizing Idea. Describe the chapter's proposed shift from building on a database to building around a protected core, with the database, web, and user treated as external details that plug into the logic.
- Database Gravity in Layered Architecture. Explain why a traditional layered architecture can lead to Database-Driven Design: the database sits at the bottom, and downward dependencies mean everything eventually points to it.
- Domain First Versus Database First. Distinguish modeling a customer's order behavior from designing tables and making classes match them. Explain why writing classes before tables does not necessarily prevent database-specific details from shaping the core.
- Database Layer Concern Leakage. Describe signs that the database layer has taken on business rules, validation, or UI formatting rather than just storing data.
- Decoupled Business Core. Explain what decoupling the core means and which outside dependencies the business logic should avoid.
- Clean Room Boundary. Explain how the clean-room analogy separates the business-logic core from the database, UI, and APIs, and why communication passes through an interface defined by the core.
- Boundary Keeper's Structural Wall. Distinguish the Boundary Keeper's job in layered architecture from its job in hexagonal architecture, and explain how a port helps keep technology concerns out of the core.
- Core Boundary Objective. Explain why protecting the core requires allowing data in and out while keeping coupling away.
- Core Rules and Flow. Distinguish the Domain, which contains entities and their rules, from the Orchestrator, which coordinates the steps of a use case.
- Inside Outside Independence. Explain the golden rule that the inside knows nothing about the outside and therefore has no references to databases, frameworks, or HTTP libraries.
- Ports as Core Contracts. Explain that ports are interfaces defining the contracts through which anything enters or leaves the core.
- Primary and Secondary Ports. Distinguish primary ports, which specify how the outside world can use the application, from secondary ports, which specify what the application needs from the outside world. Give the order-service and repository examples.
- Driving and Driven Adapters. Distinguish primary adapters, which turn outside requests into calls to a Primary Port, from secondary adapters, which implement a Secondary Port to communicate with infrastructure. Describe the OrderController and SqlOrderRepository examples.
- Inward Dependency Inversion. Explain why saving data can still flow outward to a database while the code dependency points inward: the database adapter references a Core interface. Relate that inversion to protecting the Core and extending it with adapters rather than changing it.
- USB Roles in Hexagonal Architecture. Explain how the laptop’s inside, USB port, and USB devices correspond to the core, port, and adapters in Hexagonal Architecture.
- Interchangeable Adapters Without Core Changes. Explain why respecting a port lets external devices or implementations be swapped without changing the core, using the section’s database-testing example.
- Castle Boundary and Adapter Flows. Trace how requests enter and data leaves the core through ports and adapters using the castle analogy.
- Core Focused Port Design. Explain why ports should use the core’s terms and reflect use cases rather than database tables.
- Business Policy Versus Translation. Distinguish business decisions that belong inside from fetching, storing, and translation that belong in adapters.
- Outside-In Hexagon Map. Describe how the hexagonal architecture diagram represents the boundary between inside and outside, and contrast its outside-in orientation with a layered diagram’s top-to-bottom flow.
- Self-contained domain core. Explain what sits at the center of the diagram and why it is shown without outward dependencies.
- Driving and driven flows. Trace how an initiator sends a command into the core and how the core reaches needed infrastructure through a port and adapter.
- Swappable Server Alert Channels. Explain why the server-monitoring example calls for interchangeable alert channels: an overheated server should trigger an administrator alert by SMS in production but only a console message during development. Contrast swapping plugs in Hexagonal Architecture with the environment checks a tightly coupled approach would require.
- Hardwired SMS dependency costs. Explain why tying ServerMonitor directly to Twilio makes testing and changing SMS providers difficult.
- Alert Port and Adapters. Explain why the alert port belongs inside the domain while its adapters belong outside in infrastructure. Describe how adapters turn the core’s request to send an alert into specific actions.
- Constructor Socket for Alerts. Describe how ServerMonitor stops creating its own alert dependency and instead requests it through its constructor.
- Composition Root and Swappable Plugs. Explain where the core and a chosen adapter are connected and why changing adapters does not require changing ServerMonitor.
- Visible Core and Adapter Boundary. Describe how the Server Monitor folders distinguish the core, its ports, and its adapters without requiring someone to read the code.
- Inward Project Dependencies. Explain which way dependencies run between the infrastructure and core classes in this project structure.
- Architectural Sovereignty and Reuse. Explain why ServerMonitor can be driven by a Web API, an admin CLI, or a background job without changing its core logic, and contrast that independence with a leaky system.
- Independent Core Testing. Explain why tests of the protected core can run quickly and deterministically without an internet connection or API keys.
- Decoupling Complexity Tradeoff. Justify when the extra structure of hexagonal architecture is worth its cost and when it is likely overkill.
- Core Logic Entanglement. Explain what entanglement means here and why it makes business logic difficult to run, test, and change.
- Freedom From Fixed Drivers. Describe the flexibility Cockburn wanted and how it relates to the entanglement problem.
- Application Logic Testing Obstacles. Explain why Cockburn could not easily test the application logic automatically: running it required human interaction with the GUI and a real database server.
- Purpose of the hexagon. Explain why Cockburn chose a hexagon rather than a square: it puts the application core at the center and leaves room to draw multiple outside connections without suggesting a top-to-bottom hierarchy.
- Incremental legacy migration. Explain how the Strangler Fig Pattern applies Hexagonal Architecture to a legacy application without rewriting it all at once. Describe how a new feature or high-priority fix gets a hexagonal boundary, with a Port for its needs and an Adapter to the existing legacy code or database.
- Strangler Refactor Sequence. Trace the basic refactor: isolate a new feature or bug-fix area, put its logic in a new hexagonal folder or project, connect it to legacy code or the database through an adapter that satisfies a port, and gradually move more logic until the old system is no longer needed.
- Hexagonal architecture tradeoff. Explain why choosing hexagonal architecture requires weighing its better isolation and testability against a cost, rather than adopting it automatically. Contrast this with layered architecture’s intuitive, easy-to-navigate structure.
- Hexagonal Architecture Complexity Tax. Explain why hexagonal architecture can require substantially more code than a layered approach for the same feature, and why that overhead may be unjustified for simple CRUD applications with thin business logic.
- Indirection and Navigation Tradeoff. Explain why ports can make code harder to follow in an IDE and what flexibility that indirection provides.
- Mapping Across Protected Boundaries. Explain why database, domain, and API representations are kept separate and why mappers convert between them. Describe the tradeoff between protecting the domain from database changes and doing repetitive work early in development.
- Layered versus hexagonal fit. Distinguish when the section recommends layered architecture and when it recommends hexagonal architecture.
- Benefits versus complexity tax. Justify an architecture choice by balancing its technical benefits against project constraints and the complexity it adds.
- External dependency leaks. Identify a class in an existing project that mixes core business logic with direct use of an external tool, and point to the calls that create the leak. Include system time as a possible external dependency.
- Port and Adapter Sketch. Describe how to sketch a class’s current leaky dependency and the proposed boundary: represent the class as a hexagon, show the outward dependency arrow, add an interface at the edge, and place the concrete implementation outside.
- Crypto Tracker API coupling. Explain why a hard-coded CoinGecko call makes the tracker’s value calculation fragile and hard to unit test, and how decoupling the logic through a port permits verification with a fake adapter.
- Protected Core and Inward Dependencies. Explain how hexagonal architecture separates an inside business core from the outside world and why dependencies point inward.
- Core Ports and Outside Adapters. Distinguish ports defined by the core from adapters on the outside that connect particular technologies to those ports.
- Isolated Tests and Multiple Drivers. Explain how fake adapters make isolated core tests possible and how the pattern avoids tying an application to a single way of driving it.
What it builds on
- Downward Dependency (chapter 4) · Introduces downward dependency in layered architecture.
- D – Dependency Inversion Principle (DIP) (chapter 3) · Introduces the Dependency Inversion Principle, which the introduction proposes applying to the architecture.
- Separation of Concerns (chapter 3) · Separation of concerns provides the principle this mixing violates.
- Testability in Action: Breaking Dependencies (chapter 2) · Testability as a quality affected by dependencies.
- Approach 1: Folders (common in Python/JavaScript) (chapter 4) · Folders as one way to structure layers.
- Layered Architecture (chapter 4) · The earlier top-and-bottom view of layered architecture.
- The Architect’s Role: Explainer, Scribe, Boundary Keeper, and Scout (chapter 2) · The architect’s role as a boundary keeper.
- O - Open/Closed Principle (OCP) (chapter 3) · The Open/Closed Principle named as the benefit of adding adapters without modifying the Core.
Section by section
Introduction
This chapter introduction previews decoupling business logic from external systems and the vocabulary, diagram, code, and origins of hexagonal architecture.
Introduction
The introduction identifies how a database can anchor a layered application and presents a protected core as the alternative organizing idea.
- Database Anchor in Layered Systems: Explain why a well-layered application can still depend heavily on its database, making it difficult to test or run business logic without infrastructure.
Why it matters: It explains why layers alone may not give you independently testable business logic. - Protected Core Organizing Idea: Describe the chapter's proposed shift from building on a database to building around a protected core, with the database, web, and user treated as external details that plug into the logic.
Why it matters: It gives you the central distinction to keep in mind when the chapter develops the design.
Key terms: Layers, Downward Dependency Rule, infrastructure, business logic, protected Core, Hexagonal Architecture, Ports and Adapters, Testability, Maintainability
5.2 Decoupling the Core: Breaking Free from "Database Gravity"
This section introduces how downward dependencies in a traditional layered architecture can pull design toward the database.
- Database Gravity in Layered Architecture: Explain why a traditional layered architecture can lead to Database-Driven Design: the database sits at the bottom, and downward dependencies mean everything eventually points to it.
Why it matters: It shows why organizing code into layers does not, by itself, keep the database from shaping the design.
Key terms: Four-Layer Architecture, Downward Dependency Rule, Database-Driven Design
5.2.1 The “Database First” Trap
This section shows how database-shaped domain code and misplaced database-layer logic undermine separation of concerns, testability, and resilience to database changes.
- Domain First Versus Database First: Distinguish modeling a customer's order behavior from designing tables and making classes match them. Explain why writing classes before tables does not necessarily prevent database-specific details from shaping the core.
Why it matters: It helps you spot database coupling even when a project appears to start with domain classes. - Database Layer Concern Leakage: Describe signs that the database layer has taken on business rules, validation, or UI formatting rather than just storing data.
Why it matters: These symptoms show when storage code has quietly become responsible for unrelated parts of the application. - Costs of Database Coupling: Explain how a database-shaped domain and mixed data access concerns affect changes and tests, and why folder-only layered boundaries are easy to cross.
Why it matters: It connects a seemingly convenient shortcut to harder testing and a larger impact from database changes.
Key terms: Domain First, Database First, Database Gravity, Foreign Key, SQL Row Version, data access layer, business rules, Validation in the Repository, Formatting in the Database, Separation of Concerns
5.2.2 The Clarity Engineer's Shift in Focus: Inside vs. Outside
This section shifts architectural thinking from top-and-bottom layers to inside-and-outside regions, defining decoupling the core as keeping business logic independent of outside technology.
- Inside and Outside Boundary: Distinguish thinking in layers (top and bottom) from thinking in regions (inside and outside), and describe the boundary separating the regions.
Why it matters: The inside–outside view makes it easier to identify what the core must be kept separate from. - Decoupled Business Core: Explain what decoupling the core means and which outside dependencies the business logic should avoid.
Why it matters: It keeps the business problem, rather than a particular technology, at the center of the design.
Key terms: Layers, Regions, Inside, Outside, Boundary, Boundary Keeper, Decoupling the Core, high-value business logic
5.2.3 Analogy: The "Clean Room" Lab
The clean-room analogy shows how hexagonal architecture protects business logic by making the outside world communicate through core-defined interfaces.
- Clean Room Boundary: Explain how the clean-room analogy separates the business-logic core from the database, UI, and APIs, and why communication passes through an interface defined by the core.
Why it matters: It keeps business rules separate from changes in the technologies around them. - Boundary Keeper's Structural Wall: Distinguish the Boundary Keeper's job in layered architecture from its job in hexagonal architecture, and explain how a port helps keep technology concerns out of the core.
Why it matters: A structural boundary makes it easier to protect business rules than relying on developers to remember a convention.
Key terms: Domain Core, Business Logic, Clean Room, Outside, Airlock, Interface, Boundary Keeper, Guardian of the Airlock, Port, structural walls
5.3 Inside, Ports, and Adapters
The section states the aim of protecting the core while allowing data to pass in and out without bringing coupling with it.
- Core Boundary Objective: Explain why protecting the core requires allowing data in and out while keeping coupling away.
Why it matters: This distinction explains what the architecture is trying to protect without cutting the core off from the rest of the system.
Key terms: Core, data, coupling
5.3.1 1. The Inside (The Core)
Defines the hexagonal architecture core as business logic with separate rule and workflow responsibilities, kept independent of outside technology.
- Core Rules and Flow: Distinguish the Domain, which contains entities and their rules, from the Orchestrator, which coordinates the steps of a use case.
Why it matters: This distinction keeps the rules of the business separate from the steps that carry out a use case. - Inside Outside Independence: Explain the golden rule that the inside knows nothing about the outside and therefore has no references to databases, frameworks, or HTTP libraries.
Why it matters: Keeping outside technology out of the core protects business logic from those dependencies.
Key terms: Inside, Domain, Entities, Orchestrator, Application Layer, Service Layer, Golden Rule, Outside
5.3.2 2. The Ports (The Interfaces)
This section defines ports as the core’s interface contracts and distinguishes the contracts for using the application from those for services it needs.
- Ports as Core Contracts: Explain that ports are interfaces defining the contracts through which anything enters or leaves the core.
Why it matters: Thinking of ports as contracts makes the core’s boundary easier to describe. - Primary and Secondary Ports: Distinguish primary ports, which specify how the outside world can use the application, from secondary ports, which specify what the application needs from the outside world. Give the order-service and repository examples.
Why it matters: The distinction clarifies whether a contract offers an application action or requests outside help.
Key terms: Core, Ports, Interface, contract, Primary Ports (Driving), Secondary Ports (Driven), IOrderService, IOrderRepository
5.3.3 3. The Adapters (The Translators)
Explains how driving and driven adapters translate between the outside world and the Core, while inward-pointing dependencies protect the Core from infrastructure details.
- Driving and Driven Adapters: Distinguish primary adapters, which turn outside requests into calls to a Primary Port, from secondary adapters, which implement a Secondary Port to communicate with infrastructure. Describe the OrderController and SqlOrderRepository examples.
Why it matters: The distinction shows where outside requests enter the Core and where infrastructure connections are implemented. - Translation Protects Business Logic: Explain how an adapter acts as an Anti-Corruption Layer by translating external API or database details into the Core’s language rather than letting those details enter business logic.
Why it matters: Keeping translation at the boundary lets business logic remain expressed in its own terms. - Inward Dependency Inversion: Explain why saving data can still flow outward to a database while the code dependency points inward: the database adapter references a Core interface. Relate that inversion to protecting the Core and extending it with adapters rather than changing it.
Why it matters: Separating data flow from dependency direction explains how infrastructure can change without pulling those changes into the Core.
Key terms: Primary Adapters (Driving), Secondary Adapters (Driven), Primary Port, Secondary Port, Anti-Corruption Layer, Core's language, business logic, Inversion, Dependency, Data
5.3.4 Analogy: The Universal Serial Bus (USB)
Uses a USB laptop analogy to explain how a core communicates through ports with interchangeable adapters without changing its code.
- USB Roles in Hexagonal Architecture: Explain how the laptop’s inside, USB port, and USB devices correspond to the core, port, and adapters in Hexagonal Architecture.
Why it matters: The analogy makes each part’s responsibility easier to recognize in an application. - Interchangeable Adapters Without Core Changes: Explain why respecting a port lets external devices or implementations be swapped without changing the core, using the section’s database-testing example.
Why it matters: A stable port lets you change an external connection without rewriting the application’s core.
Key terms: Inside, Core, Port, Interface, Adapter, decoupled, SQL database, file system adapter
5.3.5 A More Fun Analogy: The Castle and The Drawbridge
The castle analogy shows how ports and adapters protect the core, then identifies common ways that boundary can break down.
- Castle Boundary and Adapter Flows: Trace how requests enter and data leaves the core through ports and adapters using the castle analogy.
Why it matters: This distinction helps you keep outside formats and systems from becoming part of the core. - Swappable Outside Connections: Explain why changing an outside connection need not change the core in this analogy.
Why it matters: Keeping the core indifferent to outside implementations makes those implementations easier to replace. - Core Focused Port Design: Explain why ports should use the core’s terms and reflect use cases rather than database tables.
Why it matters: Core-focused ports prevent database details and table structure from dictating the core’s interface. - Business Policy Versus Translation: Distinguish business decisions that belong inside from fetching, storing, and translation that belong in adapters.
Why it matters: This rule of thumb helps you spot business policy that has slipped into a controller or repository.
Key terms: Core, Ports, Primary Adapters, Secondary Adapters, Domain Object, Adapters, SQL, Mongo, Leaky Port, CRUD Obsession
5.4 Diagram: The Map of the Hexagon
Introduces the hexagonal architecture diagram as an outside-in map that makes the boundary between inside and outside visible.
- Outside-In Hexagon Map: Describe how the hexagonal architecture diagram represents the boundary between inside and outside, and contrast its outside-in orientation with a layered diagram’s top-to-bottom flow.
Why it matters: This gives you a way to read the diagram without treating it as another stack of layers.
Key terms: Hexagonal Architecture diagram, Boundary, Layered Architecture diagram, outside-in
5.4.1 Reading the Map
Explains how to read a hexagonal architecture diagram: a self-contained domain at the center, distinct driving and driven sides, and a shape that represents multiple ways to connect.
- Self-contained domain core: Explain what sits at the center of the diagram and why it is shown without outward dependencies.
Why it matters: The center of the diagram shows what the architecture is protecting from external dependencies. - Driving and driven flows: Trace how an initiator sends a command into the core and how the core reaches needed infrastructure through a port and adapter.
Why it matters: The two flows distinguish what starts an action from the infrastructure the application uses to carry it out. - Hexagon as connection metaphor: Explain why the diagram uses a hexagon rather than treating its six sides as a required structure.
Why it matters: The shape helps you read the diagram without mistaking it for a fixed set of six connections or another layered stack.
Key terms: domain, Clean Room, business entities and logic, Core, driving side, driven side, initiators, Primary Adapter, Primary Port, Secondary Port
5.5 Code Snippet: The "Universal Power Outlet"
Introduces a server-monitoring example to show why swapping ports-and-adapters implementations is preferable to scattering environment checks through alerting code.
- Swappable Server Alert Channels: Explain why the server-monitoring example calls for interchangeable alert channels: an overheated server should trigger an administrator alert by SMS in production but only a console message during development. Contrast swapping plugs in Hexagonal Architecture with the environment checks a tightly coupled approach would require.
Why it matters: It shows the practical reason to keep alert delivery replaceable without making the alerting behavior depend on environment checks.
Key terms: Ports and Adapters, Server Monitoring System, SMS, Console, swapping plugs
5.5.1 The “Before” Code: The Infrastructure Anchor
This section uses a hardwired SMS example to show how infrastructure coupling makes business logic hard to test and vendors hard to change, then contrasts layered and hexagonal dependency direction.
- Hardwired SMS dependency costs: Explain why tying ServerMonitor directly to Twilio makes testing and changing SMS providers difficult.
Why it matters: The example makes the cost of coupling to an external service concrete. - Layered versus hexagonal dependencies: Distinguish the dependency direction described for a traditional layered system from the architectural inversion attributed to hexagonal architecture.
Why it matters: An interface alone does not necessarily free business logic from infrastructure dependencies.
Key terms: ServerMonitor, Twilio, Testing Nightmare, Vendor Lock-in, layered architecture, DIP, dependency arrow, infrastructure, hexagonal
5.5.2 The Hexagonal Solution: One Core, Many Plugs
Shows how an alerting core uses a domain-defined port, interchangeable infrastructure adapters, constructor injection, and a composition root to keep infrastructure choices out of business logic.
- Alert Port and Adapters: Explain why the alert port belongs inside the domain while its adapters belong outside in infrastructure. Describe how adapters turn the core’s request to send an alert into specific actions.
Why it matters: This boundary lets the core request an alert without depending on a particular delivery technology. - Constructor Socket for Alerts: Describe how ServerMonitor stops creating its own alert dependency and instead requests it through its constructor.
Why it matters: Constructor injection keeps ServerMonitor from choosing or creating its own infrastructure. - Composition Root and Swappable Plugs: Explain where the core and a chosen adapter are connected and why changing adapters does not require changing ServerMonitor.
Why it matters: A single wiring point makes infrastructure choices changeable without rewriting the alerting business logic.
Key terms: Secondary Port, Driven Port, Secondary Adapters, Inside, Outside, Domain Layer, ServerMonitor, socket, constructor, Dependency Injection
5.5.3 Making the Hexagon Visible: The Project Structure
This section shows how a Server Monitor project structure makes the hexagonal boundary visible and keeps dependencies pointing toward the core.
- Visible Core and Adapter Boundary: Describe how the Server Monitor folders distinguish the core, its ports, and its adapters without requiring someone to read the code.
Why it matters: A clear folder layout lets a developer spot the architectural boundary in the file explorer. - Inward Project Dependencies: Explain which way dependencies run between the infrastructure and core classes in this project structure.
Why it matters: Keeping references pointed inward prevents the core from depending on alerting infrastructure.
Key terms: Core, Domain, Ports, Infrastructure, Adapters, Dependencies Point In
5.5.4 The Strategic Payoff: The "Click" of the Plug
This section explains how protecting the core with ports and adapters enables reuse, isolated changes, and reliable tests, while weighing the added complexity and connecting hexagonal architecture to related approaches.
- Architectural Sovereignty and Reuse: Explain why ServerMonitor can be driven by a Web API, an admin CLI, or a background job without changing its core logic, and contrast that independence with a leaky system.
Why it matters: A protected core can serve new ways of running the application without duplicating its business rules. - Independent Core Testing: Explain why tests of the protected core can run quickly and deterministically without an internet connection or API keys.
Why it matters: Tests are easier to trust when they verify business behavior without relying on external services. - Contained Infrastructure Changes: Describe how adapters limit the effect of an external API change on the core.
Why it matters: Keeping external changes in adapters reduces the maintenance blast radius. - Decoupling Complexity Tradeoff: Justify when the extra structure of hexagonal architecture is worth its cost and when it is likely overkill.
Why it matters: The benefits of decoupling must outweigh the complexity introduced to obtain them. - Shared Core Architecture Principle: Explain what Hexagonal, Onion, LMAX, and Clean Architecture share, while identifying the broad emphasis the section gives each variation.
Why it matters: Recognizing their shared principle helps you navigate different architectural names without losing sight of protecting the core.
Key terms: Architectural Sovereignty, Core, Inside, Outside, Primary Adapter, Universal Application Logic, Testability, Port, Airplane Mode, Maintainability
5.6 The Dork Side: Cockburn's Hexagons and the Shape of Logic
The section explains the entanglement Cockburn sought to solve with Hexagonal Architecture: business logic tied to external technology is hard to test, run, and change.
- Core Logic Entanglement: Explain what entanglement means here and why it makes business logic difficult to run, test, and change.
Why it matters: It identifies the coupling Hexagonal Architecture is meant to address. - Freedom From Fixed Drivers: Describe the flexibility Cockburn wanted and how it relates to the entanglement problem.
Why it matters: It explains why freeing the core from a particular UI matters beyond making diagrams look tidy.
Key terms: entanglement, core business logic, external technologies, hard-wired, Hexagonal Architecture, business logic
5.6.1 The Origin Story: Alistair and the Weather App
This origin story explains how UI and database dependencies frustrated automatic testing of application logic, and why Cockburn questioned conventional layered-architecture drawings.
- Application Logic Testing Obstacles: Explain why Cockburn could not easily test the application logic automatically: running it required human interaction with the GUI and a real database server.
Why it matters: These testing obstacles make the need to separate application logic from external concerns concrete. - Layered Drawing Critique: Describe why Cockburn saw conventional layered-architecture drawings as part of the problem: they pictured the UI at the top and the database at the bottom, suggesting a one-way downward pull.
Why it matters: The critique explains why even the way an architecture is drawn can shape how developers think about dependencies.
Key terms: application logic, GUI, database, Layered Architecture, UI
5.6.2 The Geometry of "Enough Room"
The section explains why the hexagon is a diagramming choice, not a requirement for six ports, and why “Ports and Adapters” better names the pattern.
- Purpose of the hexagon: Explain why Cockburn chose a hexagon rather than a square: it puts the application core at the center and leaves room to draw multiple outside connections without suggesting a top-to-bottom hierarchy.
Why it matters: The drawing should help you see the core’s connections, not make you design around six sides. - Meaning of Ports and Adapters: Distinguish the pattern’s descriptive name from its geometric nickname: ports are sockets defined by the application, and adapters are plugs connecting specific technologies to them.
Why it matters: The descriptive name keeps attention on how outside technologies connect to the application rather than on the diagram’s shape.
Key terms: Application Core, ports, Hexagonal Architecture, Ports and Adapters, adapters
5.7 The Rescue Mission: Can I Migrate a Legacy App to Hexagonal?
This section explains how to migrate a legacy application incrementally by building new hexagonal logic around parts of the old system.
- Incremental legacy migration: Explain how the Strangler Fig Pattern applies Hexagonal Architecture to a legacy application without rewriting it all at once. Describe how a new feature or high-priority fix gets a hexagonal boundary, with a Port for its needs and an Adapter to the existing legacy code or database.
Why it matters: You can improve a messy application without risking a complete rewrite.
Key terms: Strangler Fig Pattern, Hexagonal boundary, Port, Adapter, legacy database
5.7.1 How to execute the "Strangler" Refactor:
This section outlines a gradual way to move legacy application logic into a hexagonal structure and cautions against doing so without considering the cost.
- Strangler Refactor Sequence: Trace the basic refactor: isolate a new feature or bug-fix area, put its logic in a new hexagonal folder or project, connect it to legacy code or the database through an adapter that satisfies a port, and gradually move more logic until the old system is no longer needed.
Why it matters: You can start isolating legacy logic without replacing the whole application at once. - Refactoring Cost Check: State why the section cautions against converting every legacy application to hexagonal architecture: the architect should consider the complexity cost before deciding to refactor.
Why it matters: The migration steps are an option, not a blanket recommendation for every legacy application.
Key terms: Seam, Hexagonal Outpost, Legacy Adapter, Port, Hexagon, Complexity Tax
5.8 The Cost of Decoupling: Why You Might Not Want (or Need!) Hexagonal Architecture
Introduces the decision of whether hexagonal architecture’s isolation and testability are worth its costs compared with layered architecture.
- Hexagonal architecture tradeoff: Explain why choosing hexagonal architecture requires weighing its better isolation and testability against a cost, rather than adopting it automatically. Contrast this with layered architecture’s intuitive, easy-to-navigate structure.
Why it matters: The benefits of stronger separation matter only if they are worth the trade-off for the application.
Key terms: Layered Architecture, Hexagonal Architecture, isolation, testability, trade-offs
5.8.1 The Complexity Tax (Overhead)
This section explains the extra code hexagonal architecture requires, when that overhead may not be worthwhile, and the distinction between a DTO and a Command Object.
- Hexagonal Architecture Complexity Tax: Explain why hexagonal architecture can require substantially more code than a layered approach for the same feature, and why that overhead may be unjustified for simple CRUD applications with thin business logic.
Why it matters: Recognizing the complexity tax helps you choose an architecture proportionate to the application. - DTO and Command Object Distinction: Distinguish a DTO from a Command Object: describe what a DTO carries and explain what calling one a Command signals about its intended use.
Why it matters: The name Command tells a reader what the data payload is meant to do without implying it contains business logic.
Key terms: Complexity Tax, Hexagonal Architecture, Layered approach, CRUD, Data Transfer Object (DTO), Command Object, Input Port, Read-Only Query
5.8.2 The "Indirection" Frustration
This section explains the code-navigation cost of using ports and adapters and the flexibility gained in return.
- Indirection and Navigation Tradeoff: Explain why ports can make code harder to follow in an IDE and what flexibility that indirection provides.
Why it matters: It helps you weigh easier technology changes against the everyday effort of finding and following the code.
Key terms: indirection, Ports, Adapters, Go to Definition
5.8.3 Mapping Fatigue
This section explains the repetitive mapping cost of keeping a hexagonal architecture’s domain separate from infrastructure and why that boundary should not be abandoned for an unmeasured performance gain.
- Mapping Across Protected Boundaries: Explain why database, domain, and API representations are kept separate and why mappers convert between them. Describe the tradeoff between protecting the domain from database changes and doing repetitive work early in development.
Why it matters: The extra conversion work buys a boundary that makes database changes less likely to disrupt domain logic. - Measured Performance Before Optimization: Justify keeping the architectural boundary rather than removing mapping solely because of a feared performance hit. State when the section says performance optimization is warranted.
Why it matters: It gives you a way to respond to performance concerns without weakening a useful boundary on speculation.
Key terms: Inside, Outside, Domain, Infrastructure, Database Entity, Mappers, performance hits, leaky code, premature optimization, clarity
5.8.4 The Architect's Decision Matrix
This section gives practical criteria for choosing layered or hexagonal architecture while weighing technical benefits against design complexity and project constraints.
- Layered versus hexagonal fit: Distinguish when the section recommends layered architecture and when it recommends hexagonal architecture.
Why it matters: These criteria help you choose an architecture that fits the application rather than defaulting to the more elaborate option. - Benefits versus complexity tax: Justify an architecture choice by balancing its technical benefits against project constraints and the complexity it adds.
Why it matters: An architecture's benefits are only worthwhile if they justify its cost in your project's circumstances.
Key terms: Layered Architecture, Hexagonal Architecture, rich business rules, core logic, complexity tax, constraints, technical benefits
5.9 Your "In Action" Mission: Refactoring to Hexagonal
This section invites readers to practice finding a hidden dependency in their own or a teammate’s code, without needing a company codebase.
5.9.1 1. The Hunt: Dig Up Your Own Skeleton
This subsection asks the reader to find places where core business logic directly uses external tools or the outside world.
- External dependency leaks: Identify a class in an existing project that mixes core business logic with direct use of an external tool, and point to the calls that create the leak. Include system time as a possible external dependency.
Why it matters: Finding a concrete leak gives you a starting point for the refactoring exercise.
Key terms: core business logic, leaks, external dependency
5.9.2 2. The Sketch: 5 Minutes on Paper
This section asks the reader to sketch a class’s leaky dependency and the proposed port-and-adapter boundary before changing code.
- Port and Adapter Sketch: Describe how to sketch a class’s current leaky dependency and the proposed boundary: represent the class as a hexagon, show the outward dependency arrow, add an interface at the edge, and place the concrete implementation outside.
Why it matters: The drawing gives you a concrete boundary to follow when you refactor. - Boundary Before Code: Explain why the section asks you to sketch before rewriting code.
Why it matters: A quick sketch helps you decide where the boundary belongs before edits obscure the design.
Key terms: hexagon, leaky dependency arrow, port, adapter, Step 3: The Sketch, boundary, leak logic
5.9.3 3. The Refactor: Steal This Example
The Crypto Portfolio Tracker example shows why hard-coding an external price API into value calculations is fragile and difficult to test.
- Crypto Tracker API coupling: Explain why a hard-coded CoinGecko call makes the tracker’s value calculation fragile and hard to unit test, and how decoupling the logic through a port permits verification with a fake adapter.
Why it matters: It gives you a concrete reason to keep an external service out of the code that calculates portfolio value.
Key terms: core business logic, CoinGecko, Port, fake adapter, unit test
5.10 Checklist
This checklist prompts readers to recall the chapter’s core ideas and briefly defines a leaky port.
- Leaky port identification: Identify a leaky port as an interface that exposes implementation details, such as SQL or HTTP types.
Why it matters: It gives you a concrete sign that an interface exposes implementation details.
Key terms: Leaky Port, SQL, HTTP types
5.11 Recap
Recaps how hexagonal architecture protects business logic through an independent core, ports, adapters, and inward-pointing dependencies, making the logic easier to test.
- Protected Core and Inward Dependencies: Explain how hexagonal architecture separates an inside business core from the outside world and why dependencies point inward.
Why it matters: This boundary keeps changing technologies from becoming dependencies of the business logic. - Core Ports and Outside Adapters: Distinguish ports defined by the core from adapters on the outside that connect particular technologies to those ports.
Why it matters: The distinction lets the core define its boundary without embedding technology-specific details. - Isolated Tests and Multiple Drivers: Explain how fake adapters make isolated core tests possible and how the pattern avoids tying an application to a single way of driving it.
Why it matters: Replaceable outside connections make business rules faster to test without requiring real external technology.
Key terms: Hexagonal Architecture, Core Business Logic, Inside vs. Outside, Golden Rule, Ports, Adapters, interfaces, Testability, Fake adapters, entanglement
Where this is used later
- The Strangler Fig in Action: Extracting "Billing" (chapter 12) · The later legacy-system extraction example builds on the idea of moving functionality gradually.
- The Strangler Fig Pattern: Safely Evolving a Legacy System (chapter 12) · The earlier Strangler refactor of legacy code.
Concepts explained in this chapter
- adapterA component in hexagonal architecture that connects a port to an external system or technology.
- portA port is an application-facing interface in hexagonal architecture that defines operations used to interact with the application core.
- application coreThe application core is the central part of a software system that contains its essential business logic while remaining isolated from external technical concerns.
- hexagonal architectureAn architectural pattern that isolates the application core from external systems through ports and adapters.
- driving adapterA hexagonal-architecture adapter that receives requests from outside the application, converts them into the core's terms, and calls a primary port.
- driven adapterAn implementation outside the application core that translates a secondary port's contract into actions involving an external system.
- secondary portA contract defined by an application core for functionality it requires from an external system.
- testabilityTestability is the degree to which software can be easily tested to verify its behavior and correctness.
- architectural sovereigntyThe property of an application core having authority over its business rules without depending on external databases, frameworks, or infrastructure.
- primary portAn interface through which an external actor invokes an application's core functionality.
- business logicBusiness logic is the application code that implements domain-specific rules and coordinates the system's behavior.
- layered architectureA structural division of software with a defined responsibility and relationships to other divisions.
- system boundaryA separation that controls how responsibilities and dependencies cross between parts of a software architecture.
- strangler fig patternA gradual modernization technique that replaces a legacy system by moving functionality into a new system until the old system is no longer needed.
- dependency inversionThe Dependency Inversion Principle states that high-level and low-level modules should depend on abstractions, while abstractions should not depend on implementation details.
- premature optimizationPremature optimization is optimizing software before a measured performance bottleneck justifies the change.
- sketchA sketch is an informal architecture diagram that represents a system’s main responsibilities and relationships without the formality of a UML diagram.
- tradeoffA tradeoff is a situation in which gaining a benefit requires accepting a cost, risk, or limitation elsewhere.
- domain layerThe architectural part of an application that contains core business knowledge, rules, logic, state, entities, value objects, and domain services.
- interfaceAn interface is a programming-language construct that defines a contract of operations without prescribing their implementation.
- complexity taxThe additional implementation complexity and maintenance burden incurred by adopting a more decoupled architectural structure.
- data layerA data layer isolates data access and persistence operations from other application responsibilities.
- anticorruption layerA boundary pattern that translates between an external system's model and an application's domain model to prevent external concepts from affecting the domain model.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
