Throughout the module we have improved Verdalia's code piece by piece: a shipping module, an OrderService class, an adapter for PagoRaíz. What is missing is the overall rule that says where everything goes and who may depend on whom. In this lesson you will see how the principles studied, applied to whole modules, give rise to an architecture: ports and adapters. With it, Verdalia will write the first automated tests in its history and will check with a real change whether scenario QS-5 is met. We will close the module with a review of the results and with a new decision record, ADR-002.

From Principles to Architecture

Every idea in the module has a large-scale version. When they are applied together and systematically, the result is no longer a well-designed class, but a way of organizing the system:

Principle or pattern In a class In the architecture
Cohesion and coupling A class with one purpose and few dependencies Modules per business area, with a public interface
Separation of concerns Data, rules, and presentation functions A business zone and an infrastructure zone
Dependency inversion OrderService depends on PaymentGateway The business does not depend on the infrastructure
Interface segregation Small interfaces per client Ports: what the business needs from the outside
Adapter PagoRaizGateway Adapters all around the business

The Dependency Rule

In any application two kinds of code coexist:

Kind What it contains Examples at Verdalia Why it changes
Domain The business rules When shipping is free, which steps confirm an order Because the business changes
Infrastructure The technical details that connect to the outside SQL and PostgreSQL, Flask, SMTP, the PagoRaíz library Because the technology or a vendor changes

The dependency rule says that the domain must not depend on the infrastructure. Code dependencies always point toward the domain, never from it outward.

In practice, the rule is checked by looking at the imports. Domain files may not contain import psycopg2, import flask, or import smtplib.

Why in that direction and not the other way around? Because the domain is the most valuable and the most stable part. Verdalia's shipping rules would exist just the same with another database or another gateway. If the domain depended on the infrastructure, every technical change would force a review of the business rules, and those rules could not be tested without having everything else running.

But the domain needs the infrastructure: orders have to be stored and they have to be charged. The apparent contradiction is resolved with the dependency inversion we saw in the lesson on SOLID. The domain declares what it needs through an interface, and the infrastructure implements it. At runtime, the service calls the PagoRaíz adapter. But in the code it is the adapter that knows the domain, and not the other way around: the dependency arrow crosses the boundary inward.

Dependency Injection Without Frameworks

If the domain only knows interfaces, someone has to hand it the real objects. That handover is called dependency injection: an object receives its collaborators from outside instead of creating them.

Form How it is done When to use it
Constructor injection Collaborators are received when the object is created The default option: the object is born complete
Parameter injection The collaborator is passed on each call When it varies from one call to the next, such as the discount policy
Attribute injection It is assigned after the object is created Best avoided: the object can be used half-configured

The place where the real objects are created and wired together is called the composition root. It should be unique and sit at the entry point. At Verdalia it is app.py:

# verdalia/app.py (excerpt)
config = load_config()
connection = psycopg2.connect(config.database_url)

publisher = EventPublisher()
publisher.subscribe("order_confirmed", inventory.deduct_stock)
publisher.subscribe("order_confirmed", notifications.notify_warehouse)

pagoraiz_client = PagoRaizClient(config.pagoraiz_key)
gateway = LoggingGateway(RetryingGateway(PagoRaizGateway(pagoraiz_client)))

order_service = OrderService(
    repository=PostgresOrderRepository(connection),
    gateway=gateway,
    notifier=SmtpNotifier(config.mail_server),
    publisher=publisher,
)

Explanation:

  • It is the only file that knows all the concrete classes. The rest of the application works with interfaces.
  • The configuration and the connection are created once and handed to whoever needs them. It is the alternative to the Singleton we saw in the previous lesson.
  • The gateway is assembled by stacking the decorators on top of the adapter. OrderService receives the result without knowing how many layers it has.
  • Reading this file is like reading the store's assembly diagram.
  • The credentials still come from config.py. Getting them out of the repository is the goal of scenario QS-4, which we will tackle in Module 5.

There are libraries that automate this assembly. For an application of Verdalia's size they are not needed: a few dozen explicit lines are easier to understand and to debug.

Hexagonal Architecture: Ports and Adapters

Hexagonal architecture, also called ports and adapters, was proposed by Alistair Cockburn in 2005. It organizes the application into a core, which contains the domain, surrounded by adapters that connect it to the outside. The hexagon is just a way of drawing it, and the number of sides means nothing.

Concept What it is In the orders module
Core The domain: business rules and operations Order and OrderService
Inbound port What the core offers: the operations that can be requested of it OrderService.confirm
Outbound port What the core needs from the outside, expressed as an interface PaymentGateway, OrderRepository, Notifier
Inbound adapter Translates an external request into a call to an inbound port The Flask web routes
Outbound adapter Implements an outbound port with a specific technology PagoRaizGateway, PostgresOrderRepository, SmtpNotifier
flowchart LR
    web["Inbound adapter: Flask web routes"]
    subgraph core["Core of the orders module"]
        inbound["Inbound port: confirm order"]
        service["OrderService and Order"]
        p1["Outbound port: PaymentGateway"]
        p2["Outbound port: OrderRepository"]
        p3["Outbound port: Notifier"]
        inbound --> service
        service --> p1
        service --> p2
        service --> p3
    end
    a1["Adapter: PagoRaizGateway"] -->|"implements"| p1
    a2["Adapter: PostgresOrderRepository"] -->|"implements"| p2
    a3["Adapter: SmtpNotifier"] -->|"implements"| p3
    web --> inbound
    a1 --> pagoraiz["PagoRaíz"]
    a2 --> db[("PostgreSQL")]
    a3 --> mail["Email server"]

Every arrow that crosses the edge of the core points inward. That is the dependency rule, drawn.

The most important consequence is that adapters are interchangeable. The same core can work with PostgreSQL or with an in-memory dictionary, and it can receive requests from a web page or from an automated test.

There are other architectures in the same family, such as onion architecture and clean architecture, formulated by Robert C. Martin. They differ in the number of rings and in the names, but they share the dependency rule. Once you understand the hexagonal one, the others are easy to recognize.

Verdalia's Orders Module

The Core

# verdalia/orders/ports.py
from abc import ABC, abstractmethod
from dataclasses import dataclass


@dataclass
class ChargeResult:
    accepted: bool
    transaction_id: str = ""


class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, reference, amount):
        """Charges the amount in euros and returns a ChargeResult."""


class OrderRepository(ABC):
    @abstractmethod
    def find(self, order_id): ...

    @abstractmethod
    def save(self, order): ...


class Notifier(ABC):
    @abstractmethod
    def send_confirmation(self, order):
        """Tells the customer that their order is confirmed."""
# verdalia/orders/service.py
from verdalia.shipping import calculate_shipping_cost


class OrderService:
    def __init__(self, repository, gateway, notifier, publisher):
        self._repository = repository
        self._gateway = gateway
        self._notifier = notifier
        self._publisher = publisher

    def confirm(self, order_id):
        order = self._repository.find(order_id)
        order.shipping_cost = calculate_shipping_cost(order.amount, order.shipping_method)
        result = self._gateway.charge(f"ORD-{order.id}", order.total)
        if not result.accepted:
            return False
        order.status = "confirmed"
        self._repository.save(order)
        self._notifier.send_confirmation(order)
        self._publisher.publish("order_confirmed", order)
        return True

Explanation:

  • ports.py gathers the three interfaces the module needs from the outside. They are the ones we discovered while applying the SOLID principles. ChargeResult is part of the gateway's contract, which is why it lives next to it.
  • The Order class, which you already know, is in domain.py.
  • OrderService is almost identical to the one from previous lessons. Look at its imports: only the shipping module appears, which is domain. There is no trace of databases, HTTP, or email.
  • The fourth collaborator is the EventPublisher from the previous lesson. It has no interface because it is a small class of our own with no external effects: one of the cases where abstracting does not pay.
  • The inbound port is the public method confirm. No interface has been created for it: in Python that would be ceremony without benefit.

The Real Adapters

# verdalia/orders/adapters/postgres_repository.py
from verdalia.orders.domain import Order
from verdalia.orders.ports import OrderRepository


class PostgresOrderRepository(OrderRepository):
    def __init__(self, connection):
        self._connection = connection

    def find(self, order_id):
        cursor = self._connection.cursor()
        cursor.execute(
            "SELECT id, customer_email, amount, shipping_method, shipping_cost, status "
            "FROM orders WHERE id = %s",
            (order_id,),
        )
        id_, email, amount, method, cost, status = cursor.fetchone()
        return Order(id_, email, float(amount), method, float(cost), status)

    def save(self, order):
        cursor = self._connection.cursor()
        cursor.execute(
            "UPDATE orders SET shipping_cost = %s, status = %s WHERE id = %s",
            (order.shipping_cost, order.status, order.id),
        )
        self._connection.commit()

Explanation:

  • The adapter imports from the domain, and not the other way around. All the SQL related to orders is gathered in this class.
  • find turns a table row into an Order object, and save goes the opposite way. For brevity, only the update of an existing order is shown.
  • It receives the connection in the constructor. The global variable connection is no longer used in this module.

The other adapters follow the same scheme:

Adapter Port Where it lives What it does
PagoRaizGateway PaymentGateway Payments module Translates to the PagoRaíz library, as we saw in the previous lesson
SmtpNotifier Notifier Notifications module Writes the email and sends it over SMTP
Web routes Inbound port orders/adapters/web.py Receives the Flask request, calls confirm, and returns the page

The payments and email adapters live in their own modules, which are the ones that know those external systems. To implement the port, they import the interface from orders. This has a consequence for the blueprint we drew in the first lesson of the module: there, orders depended on payments and notifications. Now those two arrows have been inverted, and orders no longer depends on either of them.

In-Memory Adapters and the First Automated Tests

Until today, testing the confirmation of an order required a database, a PagoRaíz account, and an email server. That is why nobody wrote tests in six years. With ports, it is enough to create fake adapters that work in memory:

# verdalia/orders/adapters/in_memory.py
from verdalia.orders.ports import (
    Notifier, OrderRepository, PaymentGateway, ChargeResult,
)


class FakeGateway(PaymentGateway):
    def __init__(self, accept=True):
        self._accept = accept
        self.charges = []

    def charge(self, reference, amount):
        self.charges.append((reference, amount))
        return ChargeResult(accepted=self._accept, transaction_id="FAKE-1")


class InMemoryOrderRepository(OrderRepository):
    def __init__(self):
        self._orders = {}

    def find(self, order_id):
        return self._orders[order_id]

    def save(self, order):
        self._orders[order.id] = order


class InMemoryNotifier(Notifier):
    def __init__(self):
        self.sent = []

    def send_confirmation(self, order):
        self.sent.append(order.id)

Explanation:

  • Each class implements a port with the bare minimum: a dictionary or a list.
  • FakeGateway can be configured to accept or decline charges, and it records every charge requested of it.
  • InMemoryNotifier sends nothing. It notes which orders would have been notified, so the test can check it.

The tests are written with unittest, the testing module that ships with Python:

# tests/test_orders.py
import unittest

from verdalia.events import EventPublisher
from verdalia.orders.adapters.in_memory import (
    FakeGateway, InMemoryNotifier, InMemoryOrderRepository,
)
from verdalia.orders.domain import Order
from verdalia.orders.service import OrderService


class ConfirmOrderTests(unittest.TestCase):
    def setUp(self):
        self.repository = InMemoryOrderRepository()
        self.notifier = InMemoryNotifier()
        self.events = []
        self.publisher = EventPublisher()
        self.publisher.subscribe("order_confirmed", self.events.append)
        self.repository.save(
            Order(id=1, customer_email="[email protected]", amount=45.0)
        )

    def create_service(self, gateway):
        return OrderService(
            self.repository, gateway, self.notifier, self.publisher
        )

    def test_accepted_payment_confirms_the_order(self):
        gateway = FakeGateway(accept=True)
        service = self.create_service(gateway)

        self.assertTrue(service.confirm(1))

        self.assertEqual(self.repository.find(1).status, "confirmed")
        self.assertEqual(gateway.charges, [("ORD-1", 49.95)])
        self.assertEqual(self.notifier.sent, [1])
        self.assertEqual(len(self.events), 1)

    def test_declined_payment_neither_confirms_nor_notifies(self):
        service = self.create_service(FakeGateway(accept=False))

        self.assertFalse(service.confirm(1))

        self.assertEqual(self.repository.find(1).status, "pending")
        self.assertEqual(self.notifier.sent, [])
        self.assertEqual(self.events, [])

    def test_order_over_60_euros_pays_no_shipping(self):
        self.repository.save(
            Order(id=2, customer_email="[email protected]", amount=63.0)
        )
        gateway = FakeGateway()

        self.create_service(gateway).confirm(2)

        self.assertEqual(gateway.charges, [("ORD-2", 63.0)])

They are run with python -m unittest tests.test_orders -v. Output, abbreviated:

test_accepted_payment_confirms_the_order ... ok
test_declined_payment_neither_confirms_nor_notifies ... ok
test_order_over_60_euros_pays_no_shipping ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Explanation:

  • A test class inherits from unittest.TestCase. Each method whose name starts with test_ is a test, and the name describes the behavior being checked.
  • setUp runs before each test. It prepares the fake adapters and stores a €45 order. That way, every test starts from a clean situation.
  • To watch the events, the test subscribes a list's append method to the publisher: every published event is recorded in self.events.
  • The tests follow three steps: arrange, act, and assert. The assertEqual, assertTrue, and assertFalse methods compare the result obtained with the expected one.
  • The first test checks the normal case: €49.95 is charged, which is the €45 of the order plus €4.95 shipping, the order is confirmed, the customer is notified, and an event is published.
  • The second checks something that could never be tested without risk before: what happens when the payment is declined.
  • All three run in under a millisecond, with no database, no network, and without charging anyone.

These tests cover the core. The real adapters need another kind of test, one that does use a database or the vendor's sandbox environment. They are slower and there are fewer of them. When we study continuous delivery, in Module 6, we will see how to run them all automatically before every deployment.

Folder Structure of the Modular Monolith

This is what the repository looks like in mid-November:

verdalia/
├── app.py                          Composition root
├── config.py
├── events.py                       EventPublisher
├── utils.py                        Being phased out: 1,480 lines left
├── catalog/                        Pending reorganization
├── cart/
├── inventory/
├── shipping/
│   ├── __init__.py                 Public interface of the module
│   ├── methods.py                  ShippingMethod and one class per method
│   └── factory.py                  Creation and public functions
├── orders/
│   ├── __init__.py
│   ├── domain.py                   Order
│   ├── ports.py                    PaymentGateway, OrderRepository, Notifier
│   ├── service.py                  OrderService
│   └── adapters/
│       ├── web.py                  Flask routes
│       ├── postgres_repository.py
│       └── in_memory.py            Fake adapters for the tests
├── payments/
│   └── pagoraiz_gateway.py         Adapter and decorators
└── notifications/
    └── smtp_notifier.py
docs/adr/
tests/
├── test_shipping.py
└── test_orders.py

Observations:

  • The top level speaks the language of the business: whoever opens the repository sees a store, not a technology.
  • Inside a module, the domain is at the root and the infrastructure is in adapters. That separation makes the dependency rule visible.
  • Not every module needs the full structure. The shipping module contains only rules: it has no ports or adapters because it does not talk to the outside.
  • It is still a monolith: one application, one deployment, and one database, as ADR-001 established.

Module Review: Scenario QS-5 and ADR-002

The Real Test

On Thursday, November 12, Andrés asked for economy shipping: delivery within 5 to 7 days for €2.95, free for orders over €60. It was exactly the stimulus of scenario QS-5. Íker made three changes.

The first, a new class in verdalia/shipping/methods.py:

class EconomyShipping(ShippingMethod):
    code = "economy"
    name = "Economy shipping (5-7 days)"

    def calculate_cost(self, amount):
        return 0.0 if amount > FREE_SHIPPING_THRESHOLD else 2.95

The second, registering it in the factory, in verdalia/shipping/factory.py, by adding EconomyShipping to the list of classes. The third, its tests, in tests/test_shipping.py:

class EconomyShippingTests(unittest.TestCase):
    def test_costs_2_95_up_to_60_euros(self):
        self.assertEqual(calculate_shipping_cost(19.80, "economy"), 2.95)
        self.assertEqual(calculate_shipping_cost(60.00, "economy"), 2.95)

    def test_is_free_above_60_euros(self):
        self.assertEqual(calculate_shipping_cost(60.01, "economy"), 0.0)

    def test_appears_among_the_cart_options(self):
        codes = [code for code, name, cost in shipping_options(45.0)]
        self.assertIn("economy", codes)

The cart, orders, and email were not touched. The cart shows what the public function shipping_options returns, the order stores the method's code, and the email shows the cost already calculated.

Measure Before With economy shipping QS-5 target
Working time 9 days 2 days 3 days or less
Modules modified Cart, orders, and notifications 1: shipping 1
Files modified 7 2, plus the test file Not defined
Verification Manual, of the whole store 3 new tests, plus the existing ones Not defined

The change went live in the deployment of Tuesday, November 17. The result should be read with caution:

  • It is a single measurement. The scenario will be considered met when it is repeated across several changes.
  • The calendar was lucky. With only two deployments a month, a request arriving one day after a deployment would have waited two weeks. That limit is not in the code but in the way of deploying, and it belongs to scenario QS-6.

The State of the Modularization

Measure October November
Dependencies between modules 19 10
Mutual dependencies 6 1, between catalog and inventory
Outgoing dependencies of orders 5 2: cart and shipping
Lines in utils.py 2,100 1,480
Automated tests 0 23
Copies of the shipping cost rule 3 1

Work remains: catalog and inventory still share the products table, and the cart still queries stock directly. The 30% of time reserved by ADR-001 will keep going to it.

ADR-002

ADR-002: Organize the modules that combine business rules and infrastructure with ports and adapters

Status: Accepted

Date: 2026-11-18

Participants: Marta decides; Íker and Lucía consulted; Andrés informed.

Context

ADR-001 established that the store would be reorganized into seven modules, but not how each one should be organized internally. In the monolith, business rules were mixed with SQL, calls to PagoRaíz, and email sending, which made them impossible to test and caused every change to affect several areas. The quality scenario affected is QS-5, on maintainability. Over six weeks this organization has been applied to the orders module, as a pilot. The constraints are those of ADR-001: a team of three people and 30% of development time.

Options considered

  • A. Modules with a public interface, with no rules about their internals. It is the simplest, but the business rules would remain tied to the infrastructure and untested.
  • B. Ports and adapters, with manual dependency injection. Separates the domain from the infrastructure and allows testing it in memory. Adds files and indirection.
  • C. Option B, plus a dependency injection library and the same full structure in all seven modules. Maximum uniformity, at the cost of a complexity the store's size does not justify.

Decision

We will organize with ports and adapters the modules that combine business rules and infrastructure: orders, payments, cart, and inventory. In them, domain code will not import infrastructure libraries. Dependencies will be injected by hand from app.py. Modules that contain only rules, such as shipping, or that barely have any, such as catalog, will keep a simpler structure. Every domain use case will have automated tests with in-memory adapters.

Consequences

Positive:

  • Business rules are tested in milliseconds, with no database or external services.
  • Replacing a vendor, or the way of communicating with it, affects only one adapter.
  • The modules are prepared for a possible future extraction, foreseen in ADR-001.

Negative:

  • More files and more indirection: following an operation means going through the port and the adapter.
  • The team has to learn and maintain the convention.
  • In-memory tests do not catch errors in the SQL or in the integration with PagoRaíz.

Risks:

  • Applying the structure mechanically where it adds nothing. Mitigated by limiting it to the modules listed.
  • Fake adapters behaving differently from the real ones.

Review conditions

It will be reviewed if the assembly in app.py exceeds 200 lines, in which case a dependency injection library will be considered; if a second module needs to charge payments, to decide where the PaymentGateway port should live; or if, after reorganizing three modules, the typical change does not stay at 3 days or less. In any case, it will be reviewed in June, together with ADR-001.

Common Mistakes and Tips

  • Letting the infrastructure sneak into the domain. An import psycopg2 in service.py “just for a quick query” undoes the architecture. The rule should be checked in every code review, and it can be automated with a small program that looks for those imports outside the adapters folders.
  • Designing ports in the vendor's image. A port with methods copied from the PagoRaíz library protects from nothing. The domain defines the port, in its own vocabulary.
  • Creating ports for everything. A port is justified when there is something external, slow, or changing on the other side. Pure functions and simple classes of your own do not need one.
  • Spreading the assembly across the whole application. If the real objects are created in several places, nobody knows how the system is assembled. The composition root must be unique.
  • Relying only on in-memory tests. They prove the rules are correct, not that the SQL works.
  • Applying the architecture to the whole application at once. Verdalia started with one module, measured the result, and then decided.
  • Practical tip. If you do not know whether something is domain or infrastructure, ask yourself whether it would still exist if the store were run with pen and paper. Free shipping over €60, yes. The SQL query, no.

Exercises

Exercise 1: Classify the Pieces

State whether each element is domain, outbound port, inbound adapter, or outbound adapter:

  1. The rule “Last units” if fewer than 5 units are in stock.
  2. A ProductRepository interface with the method find(product_id).
  3. A class that implements ProductRepository by reading a CSV file.
  4. A program that runs every night and calls OrderService to cancel unpaid orders.
  5. The InMemoryNotifier class.

Exercise 2: A New Test

Add to ConfirmOrderTests a test that checks that a €45 order with express shipping charges €53.90 and stores €8.90 as shipping cost.

Solutions

Solution to Exercise 1

  1. Domain. It is a business rule.
  2. Outbound port. It expresses what the domain needs, without saying how it is obtained.
  3. Outbound adapter. It implements the port with a specific technology.
  4. Inbound adapter. It is not a web page, but it plays the same role: it translates an external stimulus, the time of day, into a call to the core.
  5. Outbound adapter. Being fake does not change its role: it implements a port.

Solution to Exercise 2

    def test_express_order_pays_8_90_shipping(self):
        self.repository.save(
            Order(id=3, customer_email="[email protected]",
                  amount=45.0, shipping_method="express")
        )
        gateway = FakeGateway()

        self.create_service(gateway).confirm(3)

        self.assertEqual(gateway.charges, [("ORD-3", 53.9)])
        self.assertEqual(self.repository.find(3).shipping_cost, 8.90)

When run, the result is ok. The test does not check the express rate itself, which already has its tests in the shipping module, but that the service applies it and charges the correct total.

Common mistake: reusing order 1 from setUp and changing its shipping method after saving it. It works, but it makes the test harder to read. It is better for each test to create the data that sets it apart.

Conclusion

In this lesson you have seen how the module's principles turn into architecture. The dependency rule establishes that the domain does not depend on the infrastructure. Dependency injection, done by hand from a composition root, hands each piece its collaborators. And hexagonal architecture gives the parts their names: a core with the business rules, ports that express what it offers and what it needs, and interchangeable adapters that connect it to the outside.

This lesson closes Module 2. Verdalia started October with a decision, ADR-001, and a codebase in which nobody dared to touch anything. By mid-November it has a shipping module with the cost rule in a single place, an orders module organized with ports and adapters, 23 automated tests, and a first measurement of scenario QS-5: a new shipping method in 2 days, touching a single module. The way of working has been recorded in ADR-002.

Much remains to be solved. The store is still a single application on a single server, confirming an order still keeps the customer waiting while the payment is charged and the email is sent, and there are about four months left before the spring campaign. In Module 3 we will lift our eyes from the code to study the components of the system and the way they communicate. We will start with an idea we have only touched on in this lesson, when separating the domain from the infrastructure: we will see it in the lesson “Layers of an Architecture.”

© Copyright 2026. All rights reserved