An application has to work equally well for a person, for another program and for an automated test, and must not depend on which database and interface it uses. To achieve this, the core with the business logic is separated from the outside world by a boundary of explicitly declared interfaces.
Ports and adapters
The core declares ports — Cockburn calls a port a “purposeful conversation” with the outside world. A single port usually has several adapters for different technologies. Adapters come in two kinds: driving adapters call the core, driven adapters implement what the core calls.
| Part | What it is | Examples |
|---|---|---|
| Port | an interface declared by the core | order intake, order storage, notifications |
| Driving adapter | drives the actions of the core | REST controller, CLI command, automated test |
| Driven adapter | implements what the core needs | PostgreSQL storage, email delivery, message bus |
Ports are separated by meaning, not by technology. In Cockburn’s example the system warns about natural disasters through four ports: trigger data, notifications to people, an administrative interface and a subscriber database. When the need arose to receive a feed over HTTP and to send mailings by email, both were added as new adapters without touching the core — instead of a separate version of the application for every combination of interfaces.
The dependency rule
Dependencies point inwards: the core knows nothing about PostgreSQL and HTTP, and the infrastructure implements the interfaces declared by the core. The shape is beside the point: the hexagon is a neutral figure with no “main” side, all the ports on it are equal, and the number of sides means nothing.
# port — declared by the application coreclass OrderRepository(Protocol): def save(self, order: Order) -> None: ... # driven adapter — implemented by the infrastructureclass PostgresOrderRepository(OrderRepository): def save(self, order: Order) -> None: ...Why and when
- The logic is tested without a database or interface: PostgreSQL is replaced with a fake a few lines long, and such tests run in milliseconds.
- One core serves several entry points — a web API, a console, a graphical interface — without duplicating the logic.
- Infrastructure details are chosen later and changed more cheaply: switching from one database to another touches only the adapter.
The price is more interfaces and more data conversion between layers. For an application with simple logic and standard CRUD this is extra work; the benefit is noticeable where there are many business rules that need fast tests.
Alistair Cockburn described the pattern in a 2005 technical report and called it “ports and adapters” himself; the name “hexagonal architecture” survived from a drawing with a hexagon.
Sources
the term is written from these pagesVerified 8 Nov