IC Improve Code Recipes

Recipe 8.5 · Python

Validating at the Boundary and Inside the Domain

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Once a team adopts validators, the next question is where to put them. One camp validates only in the controller, and the domain objects accept anything. Another camp repeats every check in every layer until a change to a maximum length requires edits in six places. Neither holds up. The first lets a background job or a second API create invalid objects. The second drifts out of sync.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Public setters on everything mean any code can put the object into any state. The controller's validation is the only line of defense, and only for the paths that go through the controller.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Anemic order model mutated freely from anywhere (p177_r8_5_anemic_mutable_order_before.py)
"""Anemic order model mutated freely from anywhere

Source: ImproveCode, Chapter 8, Recipe 8.5 "Validating at the Boundary and Inside the Domain"
Section: The way it's often written
Book page: 177-178  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Mutable (non-frozen) dataclasses mirror the public get/set properties.
"""

from dataclasses import dataclass, field


@dataclass
class OrderItem:
    quantity: int = 0


@dataclass
class Order:
    customer_email: str | None = None
    items: list[OrderItem] = field(default_factory=list)
    status: str | None = None


def somewhere_far_away(order: Order) -> None:
    # Somewhere far away:
    order.status = "Submitted"
    order.items.append(OrderItem(quantity=-3))

The improved recipe

Split the work in two. At the boundary (API endpoint, file import, message handler) validate the shape of input and collect every error for the caller. Inside the domain, make invalid states impossible to construct: small value objects with a TryCreate factory, and entities whose methods enforce their own rules and throw when a caller breaks them.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Email value object, invariant-guarding Order, and DTO-to-domain mapper (p178_r8_5_order_domain_invariants_mapper.py)
"""Email value object, invariant-guarding Order, and DTO-to-domain mapper

Source: ImproveCode, Chapter 8, Recipe 8.5 "Validating at the Boundary and Inside the Domain"
Section: The improved recipe
Book page: 178-180  -- original C# listing
Converted from C# to Python.
email.utils.parseaddr replaces MailAddress.TryCreate; Try* out-parameters become
returned tuples. ValidationError is reused from Recipe 8.3's module.
"""

from collections.abc import Sequence
from dataclasses import dataclass
from email.utils import parseaddr
from enum import Enum, auto

from p170_r8_3_reusable_rule_validator import ValidationError


@dataclass(frozen=True)
class EmailAddress:
    value: str

    @staticmethod
    def try_create(input: str | None) -> tuple["EmailAddress | None", str | None]:
        trimmed = (input or "").strip()
        if len(trimmed) == 0 or len(trimmed) > 254:
            return None, "E-mail must be between 1 and 254 characters."
        _, parsed = parseaddr(trimmed)
        local, at, domain = parsed.rpartition("@")
        if not at or not local or not domain or parsed != trimmed:
            return None, "E-mail is not a valid address."
        return EmailAddress(trimmed), None

    def __str__(self) -> str:
        return self.value


class OrderStatus(Enum):
    DRAFT = auto()
    SUBMITTED = auto()


@dataclass(frozen=True)
class OrderItem:
    sku: str
    quantity: int


class Order:
    MAX_ITEMS = 100

    def __init__(self, customer_email: EmailAddress) -> None:
        if customer_email is None:
            raise TypeError("customer_email must not be None.")
        self._customer_email = customer_email
        self._status = OrderStatus.DRAFT
        self._items: list[OrderItem] = []

    @property
    def customer_email(self) -> EmailAddress:
        return self._customer_email

    @property
    def status(self) -> OrderStatus:
        return self._status

    @property
    def items(self) -> Sequence[OrderItem]:
        return tuple(self._items)

    def add_item(self, sku: str, quantity: int) -> None:
        if sku is None or not sku.strip():
            raise ValueError("sku must not be null or whitespace.")
        if quantity <= 0:
            raise ValueError("quantity must be greater than zero.")
        self._ensure_draft()
        if len(self._items) >= self.MAX_ITEMS:
            raise RuntimeError(
                f"An order cannot have more than {self.MAX_ITEMS} items.")
        self._items.append(OrderItem(sku.strip(), quantity))

    def submit(self) -> None:
        self._ensure_draft()
        if len(self._items) == 0:
            raise RuntimeError("An empty order cannot be submitted.")
        self._status = OrderStatus.SUBMITTED

    def _ensure_draft(self) -> None:
        if self._status is not OrderStatus.DRAFT:
            raise RuntimeError("Only draft orders can be changed.")


@dataclass(frozen=True)
class NewOrderItemDto:
    sku: str | None
    quantity: int


@dataclass(frozen=True)
class NewOrderDto:
    email: str | None
    items: Sequence[NewOrderItemDto] | None


class NewOrderMapper:
    @staticmethod
    def try_map(dto: NewOrderDto) -> tuple[Order | None, list[ValidationError]]:
        if dto is None:
            raise TypeError("dto must not be None.")
        errors: list[ValidationError] = []

        email, email_error = EmailAddress.try_create(dto.email)
        if email is None:
            errors.append(ValidationError("Email", email_error or ""))

        items = dto.items or []
        if len(items) == 0 or len(items) > Order.MAX_ITEMS:
            errors.append(ValidationError(
                "Items", f"Between 1 and {Order.MAX_ITEMS} items required."))

        for i, item in enumerate(items):
            if item.sku is None or not item.sku.strip():
                errors.append(ValidationError(f"Items[{i}].Sku",
                                              "SKU is required."))
            if item.quantity <= 0:
                errors.append(ValidationError(f"Items[{i}].Quantity",
                                              "Quantity must be positive."))

        if errors or email is None:
            return None, errors

        order = Order(email)
        for item in items:
            order.add_item(item.sku or "", item.quantity)
        return order, errors

How it works

The DTO, NewOrderDto, is a dumb bag of nullable data, because that is what arrives over the wire. NewOrderMapper.TryMap is the boundary. It checks everything, collects every problem with a path the caller can use, and only builds the domain object when the input is clean. A web endpoint turns the error list into a 400 response; a file importer writes it to a rejects file with the line number.

EmailAddress is a value object. Its constructor is private, so the only way to get one is through TryCreate, and every EmailAddress in the system is known to be valid. Methods that take an EmailAddress never check it again. MailAddress.TryCreate (added in .NET 5) does the parsing, and the extra comparison rejects inputs like "Name <a@example.com>" that parse but are not a bare address.

Order protects its own rules. There are no public setters. Items are added through AddItem, which refuses changes after submission and enforces the item limit. These checks throw, because by the time code calls AddItem with a bad quantity, the boundary has already failed to do its job. That is a bug, not a user mistake, and it should be loud.

Notice that Order.MaxItems is used by the boundary check too. The rule is defined once, in the domain, and the boundary reads it. That is how the two layers stay in sync without copying numbers around.

Variations and pitfalls

  • Exceptions or results inside the domain. I throw for broken invariants and reserve result types for outcomes the caller is expected to handle, such as "credit limit exceeded." Chapter 5 has a small Result type for that second case.
  • Persistence. EF Core can map private setters and backing fields, so a protected entity does not stop you from saving it. Configure the _items field with HasField or UsePropertyAccessMode.
  • The database is the last boundary. NOT NULL, CHECK constraints and unique indexes catch whatever the application misses, including scripts run by hand at 2 A.M. Keep them, even when the C# rules look complete.
  • Don't over-model. A value object per field is too many. Make one for values that have rules and travel widely: e-mail addresses, money, account numbers, date ranges.