liveBook · Manning

Hexagonal architecture

As explained in Go in Action, Second Edition

Ports and Adapters is an architectural pattern that isolates core application logic behind interfaces and connects those interfaces to external implementations.

An application should not have to change its core logic when an RSS library, database, or HTTP framework changes. Hexagonal architecture, also called ports and adapters, puts domain entities and interfaces at the center. Concrete adapters connect external systems to those interfaces; the domain does not import the adapters. section 11.1.2

A Go news application can establish that boundary with a few focused types:

  • Keep Article and Feed in a domain module, independent of infrastructure packages. section 11.1.2
  • Define ports for needed behavior: Fetcher retrieves a Feed, ArticleReader reads articles, and Storage adds persistence. section 11.1.2
  • Let implementation modules import the domain, never the reverse. A worker can receive a Fetcher and Storage without depending on their concrete types. section 11.1.2 section 11.3.3
Figure 11.4 Hexagonal architecture: Domain at the center with ports and adapters

The diagram shows the domain at the center, with interfaces as ports and external implementations as adapters. section 11.1.2

An RSS adapter

RSSReader implements domain.Fetcher using gofeed. Its FetchFeed method converts library-specific feed and item values into domain Feed and Article values before returning them. The declaration `var _ domain.Fetcher = (*RSSReader)(nil)` makes an interface mismatch a compile-time error. Replacing the RSS library would change this adapter, not the domain types or code that consumes Fetcher. section 11.3.3 section 11.1.2

The same boundary helps testing: a mock Fetcher can return predetermined data in place of a live RSS reader. The practical test of the design is whether consumers work with either implementation through the same interface. section 11.1.2 section 11.4

How Go in Action, Second Edition covers it

How deep it goes
Defines ports and adapters, then works through an RSS adapter's type conversion and compile-time interface check.
Examples
Illustrates a gofeed-backed RSS reader, domain feed and article types, and a worker that fetches and stores articles.
What it assumes
Assumes familiarity with Go packages and interfaces while showing the specific domain interfaces needed for the application.
What you can do after
Build it from scratch by defining domain ports, implementing an RSS adapter, and wiring a worker through interfaces.
How it connects
Connects domain-driven design, dependency inversion, interface substitution, Go modules, and test doubles.

Also explained in

Compare how 6 books explain hexagonal architecture →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.