CodePark/ questions / Layered, clean & hexagonal architecture
START PRACTICINGPRACTICE
Backend question · Software design & patterns › Layered, clean & hexagonal architecture

Explain hexagonal architecture (ports and adapters). What are ports, adapters, and the driving and driven sides?

Hexagonal architecture puts the application core in the middle and keeps it independent of everything it talks to. Alistair Cockburn created this idea. The core talks to the outside world only through ports and adapters:

  • A port is an interface. The application defines it in its own terms.
  • An adapter connects one specific technology to a port.

There are two sides:

  • The driving (primary) side is where actors use the application. An HTTP controller, a CLI, a message consumer or a test calls a port, such as a PlaceOrder use case.
  • The driven (secondary) side is where the application uses other things. The application calls ports like OrderRepository or PaymentGateway. Adapters such as PostgresOrderRepository or StripePaymentGateway implement those ports.

The hexagon shape has no special meaning. It only leaves room to draw many ports.

Why use it? You can run and test the core from tests with in-memory adapters, so no real database or network is needed. You can also swap a technology by writing a new adapter, without changing the core.

  • The application core is isolated from technology.
  • Ports are interfaces that the application owns.
  • Adapters translate between a technology and a port.
  • The driving side calls the app, and the app calls the driven side.
  • You can test the core with in-memory adapters.