JAVA-270 · Lesson 8 of 12 · 25 min
Hexagonal architecture and ports and adapters
▶ Video coming soon A video version of this lesson is on the way.
Tuesday, March 7, 2028. Leif is back, with a sheet of paper on which he has drawn a hexagon. Last week's layers, he says, have one weakness that matters a lot at Second Gear: in the classic picture the business rules sit on top of the storage, so you cannot run the rules without the spreadsheet, the till or the text-message service. And Odile's plans keep adding new ways in and out. The counter screen, the website Hamza will build in his web services course, a nightly report, Velotek's price service and the new text-message provider are all outside things the core rules must talk to. Tonight's architecture puts the rules in the middle and everything else around the edge.
The idea
Hexagonal architecture, also called ports and adapters, was described by Alistair Cockburn in 2005. Its goal is to let an application be driven equally well by people, by other programs, by automated tests or by batch scripts, and to be developed and tested in isolation from its eventual devices and databases. The application's core, holding the domain and the use cases, sits in the middle. Everything it talks to is outside: user interfaces, files, databases, other services, clocks.
The core talks to the outside world only through ports, which are interfaces defined by the core in its own terms. Outside things connect to the ports through adapters, classes that translate between the port and a particular technology. The hexagon shape has no special meaning; Cockburn drew it to leave room for several ports and to get away from the top-and-bottom picture of layers, in which the user interface and the database look like different kinds of thing. In a hexagon they are both just outside.
Driving and driven sides
Ports come in two kinds. Driving ports, also called primary or inbound ports, are the things the outside world asks the core to do: sell a part, book a repair, quote a rental. They are usually interfaces implemented by the core's use cases and called by driving adapters such as the counter screen, a web controller or a test. Driven ports, also called secondary or outbound ports, are the things the core needs from the outside world: load and save parts, look up a price, send a text message, tell the time. The core declares them as interfaces, and driven adapters implement them for particular technologies.
The crucial point is the direction of the dependencies. Every adapter depends on the core, because it implements or calls a port the core defines. The core depends on nothing outside itself. That is the dependency inversion principle from lesson 2 applied to the whole program: storage and devices are details that plug into the policy, not foundations the policy stands on.
| Port | Kind | Defined by | Adapters at Second Gear |
|---|---|---|---|
| SellPart | Driving | Core (use case interface) | Counter screen, website, test suite |
| BookRepair | Driving | Core | Counter screen, phone booking screen, test suite |
| PartCatalog | Driven | Core | Parts spreadsheet, later a database; in-memory for tests |
| PriceList | Driven | Core | Velotek web service; fixed table for tests |
| Notifier | Driven | Core | Text-message provider, email; recording fake for tests |
| Clock | Driven | java.time | System clock; fixed clock for tests |
A small core
Here is the core of a small part of the counter program, with one driving port and three driven ports, and with in-memory adapters plugged in. Everything above the comment line is the core; everything below it is adapters and wiring.
import java.time.*;
import java.util.*;
public class Main {
// ---- core: domain, ports and use case ----
record Part(String code, int onHand, int minimum) {
Part take(int n) {
if (n > onHand) throw new IllegalArgumentException("only " + onHand + " " + code + " left");
return new Part(code, onHand - n, minimum);
}
boolean isLow() { return onHand < minimum; }
}
interface SellPart { String sell(String code, int qty); }
interface PartCatalog { Part find(String code); void save(Part p); }
interface Notifier { void tell(String who, String text); }
static final class SellPartService implements SellPart {
private final PartCatalog catalog; private final Notifier notifier; private final Clock clock;
SellPartService(PartCatalog c, Notifier n, Clock k) { catalog = c; notifier = n; clock = k; }
public String sell(String code, int qty) {
Part after = catalog.find(code).take(qty);
catalog.save(after);
if (after.isLow()) notifier.tell("Kofi", code + " low at " + LocalTime.now(clock));
return "sold " + qty + " " + code + ", " + after.onHand() + " left";
}
}
// ---- adapters and wiring ----
static final class InMemoryCatalog implements PartCatalog {
final Map<String, Part> parts = new TreeMap<>();
public Part find(String code) { return parts.get(code); }
public void save(Part p) { parts.put(p.code(), p); }
}
public static void main(String[] args) {
InMemoryCatalog catalog = new InMemoryCatalog();
catalog.save(new Part("TUBE-700x25", 12, 10));
List<String> sent = new ArrayList<>();
Notifier recorder = (who, text) -> sent.add(who + ": " + text);
Clock clock = Clock.fixed(Instant.parse("2028-03-07T15:20:00Z"), ZoneId.of("America/New_York"));
SellPart sell = new SellPartService(catalog, recorder, clock);
System.out.println(sell.sell("TUBE-700x25", 1));
System.out.println(sell.sell("TUBE-700x25", 2));
System.out.println("messages: " + sent);
}
}sold 1 TUBE-700x25, 11 left sold 2 TUBE-700x25, 9 left messages: [Kofi: TUBE-700x25 low at 10:20]
What this code does
The core defines the SellPart port that callers use and the PartCatalog and Notifier ports it needs, and the use case depends only on those interfaces and a Clock. The adapters plugged in here are an in-memory catalog, a lambda that records messages instead of sending them, and a fixed clock. The low-stock message appears only after the second sale, when 9 tubes are left, below the minimum of 10.
Nothing in the core knows about the spreadsheet, the text-message provider or the counter screen. That is what makes the next three examples possible: a second way in, a second way to store parts and fast, repeatable tests, all without changing a line of the core.
Several driving adapters
A driving adapter turns some outside input into a call on a driving port, and turns the result back into whatever form its caller expects. The counter screen does it with buttons; the planned website will do it with web requests. The sketch below uses a text command such as the ones a web request or a script might send, and shows that the same port serves both.
import java.util.*;
public class Main {
interface SellPart { String sell(String code, int qty); }
static final class FakeCore implements SellPart {
private final Map<String, Integer> stock = new TreeMap<>(Map.of("BELL", 3));
public String sell(String code, int qty) {
int left = stock.getOrDefault(code, 0) - qty;
if (left < 0) throw new IllegalArgumentException("not enough " + code);
stock.put(code, left);
return qty + " " + code + " sold, " + left + " left";
}
}
static final class CounterScreenAdapter {
private final SellPart port;
CounterScreenAdapter(SellPart port) { this.port = port; }
void click(String code, String qtyBox) {
try { System.out.println("[screen] " + port.sell(code, Integer.parseInt(qtyBox))); }
catch (IllegalArgumentException e) { System.out.println("[screen] Sorry: " + e.getMessage()); }
}
}
static final class WebAdapter {
private final SellPart port;
WebAdapter(SellPart port) { this.port = port; }
String handle(String request) {
String[] p = request.split(" ");
try { return "200 OK {\"result\": \"" + port.sell(p[2], Integer.parseInt(p[3])) + "\"}"; }
catch (NumberFormatException e) { return "400 Bad Request"; }
catch (IllegalArgumentException e) { return "409 Conflict {\"error\": \"" + e.getMessage() + "\"}"; }
}
}
public static void main(String[] args) {
SellPart core = new FakeCore();
new CounterScreenAdapter(core).click("BELL", "2");
WebAdapter web = new WebAdapter(core);
System.out.println("[web] " + web.handle("POST /sell BELL 1"));
System.out.println("[web] " + web.handle("POST /sell BELL 1"));
System.out.println("[web] " + web.handle("POST /sell BELL two"));
}
}[screen] 2 BELL sold, 1 left
[web] 200 OK {"result": "1 BELL sold, 0 left"}
[web] 409 Conflict {"error": "not enough BELL"}
[web] 400 Bad RequestWhat this code does
Two driving adapters, one for the counter screen and one for web-style requests, both call the same SellPart port. Each translates its own kind of input into a call and translates the result or the exception into its own kind of output: a friendly sentence for the screen, a status code and a small JSON body for the web. The core never learns which adapter called it.
Mapping errors at the edge is one of the adapter's main jobs. The core throws an exception that means not enough stock in business terms; the web adapter turns it into a 409 Conflict, the screen adapter into a sentence. Neither status codes nor sentences belong in the core.
Swapping a driven adapter
A driven adapter implements a port for one technology. Because every adapter for a port must behave the same way from the core's point of view, a good habit is to write one contract test for the port and run it against every adapter. If the spreadsheet adapter and the in-memory adapter both pass it, the core can use either.
import java.util.*;
public class Main {
record Part(String code, int onHand) {}
interface PartCatalog { Optional<Part> find(String code); void save(Part p); }
static final class InMemoryCatalog implements PartCatalog {
private final Map<String, Part> m = new HashMap<>();
public Optional<Part> find(String code) { return Optional.ofNullable(m.get(code)); }
public void save(Part p) { m.put(p.code(), p); }
}
static final class SpreadsheetCatalog implements PartCatalog {
private final List<String> lines = new ArrayList<>(List.of("code;on_hand"));
public Optional<Part> find(String code) {
return lines.stream().skip(1).map(l -> l.split(";")).filter(f -> f[0].equals(code))
.map(f -> new Part(f[0], Integer.parseInt(f[1]))).findFirst();
}
public void save(Part p) {
lines.removeIf(l -> l.startsWith(p.code() + ";"));
lines.add(p.code() + ";" + p.onHand());
}
}
static List<String> contract(PartCatalog c) {
List<String> failures = new ArrayList<>();
if (c.find("BELL").isPresent()) failures.add("missing part should be empty");
c.save(new Part("BELL", 3));
if (!c.find("BELL").equals(Optional.of(new Part("BELL", 3)))) failures.add("saved part should be found");
c.save(new Part("BELL", 2));
if (c.find("BELL").get().onHand() != 2) failures.add("second save should replace the first");
return failures;
}
public static void main(String[] args) {
for (PartCatalog c : List.of(new InMemoryCatalog(), new SpreadsheetCatalog())) {
List<String> f = contract(c);
System.out.println(c.getClass().getSimpleName() + ": " + (f.isEmpty() ? "passes the contract" : f));
}
}
}InMemoryCatalog: passes the contract SpreadsheetCatalog: passes the contract
What this code does
PartCatalog has two driven adapters, one keeping parts in a map and one keeping them as semicolon-separated lines like the shop's spreadsheet. The contract method checks the three promises every catalog must keep: an unknown part is empty, a saved part can be found, and saving again replaces it. Both adapters pass, so the core can be given either one.
The port's find method returns Optional<Part> rather than null. Ports are the core's own interfaces, so they can say exactly what the core needs, including that a part may not exist; it is the adapter's job to translate whatever the technology does, such as an empty row or a missing file, into that answer.
Testing the core
The biggest practical benefit of ports and adapters is testing. With in-memory adapters and a fixed clock, a test of the core runs in milliseconds, needs no files, network or till, and gives the same result every time. Hamza's testing course used JUnit; to keep this lesson's examples runnable on their own, the next example checks the core with plain assertions printed as pass or fail.
import java.time.*;
import java.util.*;
public class Main {
record Booking(String customer, LocalDateTime start) {}
interface BookingStore { List<Booking> on(LocalDate day); void add(Booking b); }
static final class BookRepair {
private final BookingStore store; private final Clock clock;
BookRepair(BookingStore store, Clock clock) { this.store = store; this.clock = clock; }
String book(String customer, LocalDateTime start) {
if (!start.isAfter(LocalDateTime.now(clock))) return "refused: that time has passed";
if (start.getHour() < 9 || start.getHour() > 15) return "refused: outside repair hours";
long same = store.on(start.toLocalDate()).stream().filter(b -> b.start().equals(start)).count();
if (same >= 2) return "refused: slot full";
store.add(new Booking(customer, start));
return "booked " + customer;
}
}
static final class MemoryStore implements BookingStore {
final List<Booking> all = new ArrayList<>();
public List<Booking> on(LocalDate d) { return all.stream().filter(b -> b.start().toLocalDate().equals(d)).toList(); }
public void add(Booking b) { all.add(b); }
}
static int failures = 0;
static void check(String name, String actual, String expected) {
boolean ok = actual.equals(expected);
if (!ok) failures++;
System.out.println((ok ? "pass " : "FAIL ") + name + (ok ? "" : ": got " + actual));
}
public static void main(String[] args) {
Clock now = Clock.fixed(Instant.parse("2028-03-07T14:00:00Z"), ZoneId.of("America/New_York"));
LocalDateTime sat10 = LocalDateTime.of(2028, 3, 11, 10, 0);
BookRepair core = new BookRepair(new MemoryStore(), now);
check("first booking", core.book("Ana", sat10), "booked Ana");
check("second booking", core.book("Ben", sat10), "booked Ben");
check("third is refused", core.book("Cy", sat10), "refused: slot full");
check("past time refused", core.book("Di", LocalDateTime.of(2028, 3, 6, 10, 0)), "refused: that time has passed");
check("evening refused", core.book("Ed", LocalDateTime.of(2028, 3, 11, 17, 0)), "refused: outside repair hours");
System.out.println(failures == 0 ? "all checks passed" : failures + " checks failed");
}
}pass first booking pass second booking pass third is refused pass past time refused pass evening refused all checks passed
What this code does
The BookRepair use case is tested with an in-memory booking store and a clock fixed at 9:00 am on March 7, 2028, so every check gives the same answer on every run. Each check states the expected result of one rule: two bookings per slot, no past times and only repair hours. Because no file, network or screen is involved, the whole set runs in a fraction of a second.
Where the hexagon fits
Hexagonal architecture has close relatives. Jeffrey Palermo's onion architecture (2008) and Robert C. Martin's clean architecture (2012) draw the same idea as concentric circles: the domain at the center, use cases around it, adapters and frameworks on the outside, and every dependency pointing inward. The details and names differ; the dependency rule is the same in all three.
It is not free. Every port is an interface and every outside thing needs an adapter, which is more code than calling the spreadsheet directly. For a script that runs once, it is too much. For a program like CounterApp, which has several ways in, several ways out, rules that change every season, and a planned website that should reuse the rules, it is what Leif recommends. He also points out that a hexagon can grow gradually: start by putting a port in front of the one thing that hurts most, which at Second Gear is the spreadsheet.
| Question | Layered (lesson 7) | Ports and adapters |
|---|---|---|
| What is at the center? | Nothing; layers are stacked | The domain and use cases |
| Does the domain depend on storage? | Often, in the classic form | Never; storage implements a port |
| How are user interfaces and databases treated? | Top and bottom, different kinds of thing | Both are outside, connected by adapters |
| How are rules tested? | Often with real or partly real storage | With in-memory adapters, quickly |
| Cost | Fewer interfaces | An interface per port and an adapter per technology |
Try it yourself
Write an in-memory adapter
The starter has a PriceList port and a core QuoteService that needs it. Write an adapter FixedPrices implements PriceList backed by a Map, so the service can be run without Velotek. A missing part should return 0.
The program should print 3 x TUBE-700x25 = 2697 and 1 x SPOKE-286 = 0.
import java.util.*;
public class Main {
interface PriceList { int cents(String code); }
static final class QuoteService {
private final PriceList prices;
QuoteService(PriceList prices) { this.prices = prices; }
String quote(String code, int qty) { return qty + " x " + code + " = " + prices.cents(code) * qty; }
}
public static void main(String[] args) {
QuoteService q = new QuoteService(code -> { throw new IllegalStateException("Velotek is offline"); });
try { System.out.println(q.quote("TUBE-700x25", 3)); }
catch (IllegalStateException e) { System.out.println(e.getMessage()); }
}
}Try it yourself
Write a driving adapter
Write a driving adapter class ScriptAdapter with a method run(List<String> lines) that calls the BookRepair port for each line of the form NAME HOUR and prints the port's answer. Lines that cannot be read should print skipped: LINE instead of crashing.
The program should print booked Ana at 10, skipped: Ben ten and booked Cy at 11.
import java.util.*;
public class Main {
interface BookRepair { String book(String customer, int hour); }
public static void main(String[] args) {
BookRepair core = (customer, hour) -> "booked " + customer + " at " + hour;
for (String line : List.of("Ana 10", "Ben ten", "Cy 11")) {
String[] p = line.split(" ");
if (!p[1].matches("[0-9]+")) { System.out.println("stopped at: " + line); return; }
System.out.println(core.book(p[0], Integer.parseInt(p[1])));
}
}
}Common mistakes
MistakeLetting the core import adapter classes.
InsteadThe core defines ports; adapters implement or call them, so every dependency points inward.
MistakeDesigning ports after one technology, such as spreadsheet rows.
InsteadDesign ports in the core's own terms and translate in the adapter.
MistakePutting status codes or screen text in the core.
InsteadMap results and exceptions to each caller's form in the driving adapter.
MistakeTesting the core with real files and services.
InsteadPlug in in-memory adapters and a fixed clock for fast, repeatable tests.
MistakeBuilding ports for everything on the first day.
InsteadStart with a port in front of the dependency that hurts most and grow from there.
Summary and key terms
- Hexagonal architecture, or ports and adapters, described by Alistair Cockburn in 2005, puts the domain and use cases at the center and everything else outside.
- The core talks to the world only through ports, interfaces it defines in its own terms.
- Driving ports are what the world asks the core to do and are called by driving adapters such as screens, web controllers and tests.
- Driven ports are what the core needs from the world and are implemented by driven adapters for files, services and clocks.
- Every dependency points toward the core, which is dependency inversion applied to the whole program.
- Driving adapters translate input and map errors to their callers' forms.
- Contract tests check that every adapter for a port keeps the same promises.
- In-memory adapters and a fixed clock make the core fast and repeatable to test.
- Onion and clean architecture express the same inward dependency rule as circles.
- Hexagonal architecture
- An architecture with the application core in the middle and all outside things connected through ports and adapters.
- Ports and adapters
- Another name for hexagonal architecture.
- Core
- The domain and use cases at the center of a hexagonal design.
- Port
- An interface defined by the core for talking to the outside world.
- Driving port
- A port through which the outside world asks the core to do something.
- Driven port
- A port through which the core asks the outside world for something it needs.
- Adapter
- A class that connects a port to one particular technology.
- Driving adapter
- An adapter that turns outside input, such as a click or a request, into calls on a driving port.
- Driven adapter
- An adapter that implements a driven port for a technology such as a file or a web service.
- Contract test
- A test that every implementation of an interface must pass.
- Onion architecture
- A related architecture drawn as rings, with the domain at the center.
- Clean architecture
- Robert C. Martin's version of the same inward dependency rule.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Is the counter screen a driving or a driven adapter?
Show answer
Driving: it calls the core's ports in response to clicks.
Who defines the PartCatalog interface, the core or the spreadsheet code?
Show answer
The core; the spreadsheet adapter implements it.
The core throws an exception for not enough stock. What does the web adapter do with it?
Show answer
Maps it to a response such as 409 Conflict with a message.
What does a contract test check?
Show answer
That every adapter for a port keeps the same promises.
Why does the booking test use a fixed clock?
Show answer
So past-time checks give the same result on every run.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.