5 Hexagonal Architecture: Protecting the Core: The Power of Ports and Adapters
This chapter covers
- Decoupling your core business logic from external distractions like databases and user interfaces.
- Mastering the essential vocabulary of the pattern: the Inside (Domain), Ports (Interfaces), and Adapters (Implementations).
- Visualizing the architecture and its boundaries using the classic Hexagon diagram.
- Implementing the pattern in code to see how Ports and Adapters work in practice.
- Exploring the origin story of the pattern and why Alistair Cockburn created it.
5.1 Introduction
In Chapter 4, we brought order to chaos by organizing our code into Layers. We used the Downward Dependency Rule to ensure our Presentation layer didn't tangle with our Data Access layer. It was a huge step forward from the "junk drawer" we fought against in Chapter 3. However, as a Clarity Engineer, you might have noticed a subtle, nagging issue with the classic layered approach. Even with good layers, the database often sits at the bottom of the stack, acting as the heavy anchor that the entire application depends on.
5.2 Decoupling the Core: Breaking Free from "Database Gravity"
5.2.1 The “Database First” Trap
5.2.2 The Clarity Engineer's Shift in Focus: Inside vs. Outside
5.2.3 Analogy: The "Clean Room" Lab
5.3 Inside, Ports, and Adapters
5.3.1 1. The Inside (The Core)
5.3.2 2. The Ports (The Interfaces)
5.3.3 3. The Adapters (The Translators)
5.3.4 Analogy: The Universal Serial Bus (USB)
5.3.5 A More Fun Analogy: The Castle and The Drawbridge
5.4 Diagram: The Map of the Hexagon
5.4.1 Reading the Map
5.5 Code Snippet: The "Universal Power Outlet"
5.5.1 The “Before” Code: The Infrastructure Anchor
5.5.2 The Hexagonal Solution: One Core, Many Plugs
5.5.3 Making the Hexagon Visible: The Project Structure
5.5.4 The Strategic Payoff: The "Click" of the Plug
5.6 The Dork Side: Cockburn's Hexagons and the Shape of Logic
5.6.1 The Origin Story: Alistair and the Weather App
5.6.2 The Geometry of "Enough Room"
5.7 The Rescue Mission: Can I Migrate a Legacy App to Hexagonal?
5.7.1 How to execute the "Strangler" Refactor:
5.8 The Cost of Decoupling: Why You Might Not Want (or Need!) Hexagonal Architecture
5.8.1 The Complexity Tax (Overhead)
5.8.2 The "Indirection" Frustration
5.8.3 Mapping Fatigue
5.8.4 The Architect's Decision Matrix
5.9.1 1. The Hunt: Dig Up Your Own Skeleton