Multiple Adapters for One Port
You'll learn how to swap out infrastructure implementations seamlessly by creating multiple adapters for the same port interface.
The Core Idea
In hexagonal architecture, a port defines what your application needs (an interface), while an adapter provides how to do it (an implementation). The beauty of this separation is that you can write multiple adapters for the same port without touching your core business logic.
Think of it like a power outlet (port). Your laptop needs electricity, but it doesn't care whether that electricity comes from a wall socket, a portable battery pack, or a solar generator. Each power source is a different adapter, but your laptop works with all of them through the same port standard.
Why Multiple Adapters Matter
You might need different adapters for:
- Testing: A real database adapter vs. an in-memory test adapter
- Environments: Cloud storage in production vs. local filesystem in development
- Migration: Gradually replacing an old system with a new one
- A/B testing: Comparing two implementations side-by-side
Example Without Code
Imagine your application has a NotificationPort that defines "send a notification to a user." You could implement:
- An
EmailAdapterthat sends actual emails via SMTP - A
ConsoleAdapterthat prints to stdout for local testing - A
MockAdapterthat records calls for unit tests - An
SMSAdapterthat sends text messages instead
Your core application only knows about NotificationPort. You decide at startup or configuration time which adapter to plug in. The business logic remains identical across all scenarios.
Key Takeaway: Multiple adapters for one port give you flexibility to swap implementations based on context (test vs. production, different vendors, gradual migration) without changing your application's core logic—dependency inversion in action.