# Tackling Complex Business Logic
> **In one sentence:** for complex logic, put data and behavior together in objects that speak the
> ubiquitous language and **protect their own rules**, so nothing outside can break them.

## Where this comes from

The **domain model** pattern was first named in Fowler's *Patterns of Enterprise Application
Architecture*. Eric Evans's *Domain-Driven Design* then supplied its building blocks (aggregates,
value objects and so on), which are often called "tactical DDD". These notes follow the book in
calling the pattern *domain model* and treating the rest as its building blocks. You can do DDD
without them.

## Domain model

Use it when the logic is about **state transitions, business rules and invariants** (rules that
must *always* hold), not CRUD screens. Think of a co-working space booking flow:

- Members book desks or rooms for time slots. Rooms have capacity limits.
- Bookings unconfirmed 15 minutes before the start are released.
- Premium members can book further ahead and get priority on waitlists.
- No-shows three times in a month lose booking rights for a week.

Rules like these depend on each other. Spread them across active records and scripts and they'll
be duplicated and eventually contradict each other.

**Two design principles:**

- **No accidental complexity.** Domain objects are plain objects with no database calls, framework
  base classes or infrastructure inside them.
- **Speak the language.** Because the objects are free of technology, their names and methods can
  follow the ubiquitous language directly.

## Value objects

An object **defined entirely by its values**. It has no ID. Two `Money(25, "EUR")` instances are
the same money, and changing any field gives you a *different* value.

**Why bother?** Using raw strings and ints for business concepts ("primitive obsession") scatters
validation and meaning everywhere. Compare `email: str` with `email: EmailAddress`. The value
object validates itself once, carries its meaning in its type, and collects related behavior in
one place.

```python
@dataclass(frozen=True)          # immutable, compared by value
class Money:
    amount: Decimal
    currency: str

    def add(self, other: "Money") -> "Money":
        if other.currency != self.currency:
            raise CurrencyMismatch()
        return Money(self.amount + other.amount, self.currency)   # new instance
```

- **Immutable.** Operations return new instances. That makes them side-effect free and safe to
  share across threads.
- **Value equality.** Equality must compare fields. Many languages have record or dataclass types that do this for you.
- **Rich behavior**, not just validation: a `Duration` that converts units, a `PhoneNumber` that
  knows its country, a `DateRange` that checks overlaps.
- **Use them as much as possible**, especially for things that *describe* other objects: names,
  statuses, amounts, addresses. **Always model money as a value object**, because primitives
  cause rounding and precision bugs.
- Fun fact: the built-in string type in most languages is already a value object (immutable, with operations that return new strings).

## Entities and aggregates

### Entity

The opposite of a value object: it **needs an explicit ID** because two instances with identical
data can still be different things. Two members both called "Priya Shah" are still two people.
The ID itself is usually a value object, it shouldn't change, and the rest of the entity's state
is expected to change over time. Entities don't stand alone in this pattern; they live **inside aggregates**.

### Aggregate

An entity (or a cluster of entities and value objects) whose job is to **keep its data consistent**.

- **Consistency boundary.** Only the aggregate's own methods may change its state. Everyone else
  can only read it. Every change goes through a **command** on its public interface, as a method
  (`booking.confirm()`) or a command object (`booking.execute(Confirm(...))`). The aggregate
  validates the input and enforces every relevant rule.
- **Thin application layer.** Outside code just does *load → run command → save → return result*.
  All the rules live in the aggregate, in one place.
- **Concurrency control is mandatory.** Keep a `version` field and only save if the stored
  version still matches the one you loaded. Otherwise someone else changed it first, so reload and retry.

```sql
UPDATE bookings SET status = :status, version = version + 1
WHERE id = :id AND version = :expected_version;   -- 0 rows means a conflict
```

- **Transaction boundary.** An aggregate is saved atomically, and **one aggregate instance per
  transaction**. Needing to change two aggregates in one transaction means the boundaries are
  wrong (or it's a job for Chapter 9's patterns).
- **A hierarchy of entities.** If several objects must change together or depend on each other's
  rules, they belong in the same aggregate: a `Booking` with its `CheckIn` records, for example.
  That's where the name comes from.
- **Keep it small.** Include only what the rules need to be *strongly* consistent. Reference
  everything else **by ID** (`member_id`, `room_id`). Test: *if this data were slightly out of
  date, could the aggregate make a wrong decision?* If yes, it goes inside. If no, it stays out.
- **Aggregate root.** One entity is the entry point. Inner entities are changed only through the
  root (`booking.record_check_in(...)`, never `check_in.save()` directly).

## Domain events

A message saying **something significant happened** in the business. It's named in the **past
tense** (`BookingConfirmed`, `SlotReleased`, `MemberSuspended`) and carries the data subscribers need.

```json
{ "event_type": "booking-released", "booking_id": "b-4821",
  "reason": "not-confirmed-in-time", "occurred_at": "2026-11-20T09:45:00Z" }
```

Events are part of an aggregate's public interface. The aggregate records them, and other
aggregates, processes or systems subscribe and react. Chapter 9 shows how to publish them reliably.
Name everything (the aggregate, its fields, commands and events) in the ubiquitous language.

## Domain services

Some logic doesn't belong to any single aggregate or value object, usually a calculation that
needs data from several sources. Put it in a **domain service**: a **stateless** object that hosts
business logic.

*Example:* computing a booking's confirmation deadline might need the room's policy, the member's
tier and the building's opening hours. A `ConfirmationDeadlinePolicy` service reads all three and
returns the deadline.

- It's good for **reading** several aggregates. It is **not** a loophole for *changing* several in
  one transaction; that rule still holds.
- "Service" here has nothing to do with microservices or SOA. It's just a home for logic.

## Why this tames complexity

One useful way to measure complexity is **degrees of freedom**: how many independent values you
need to describe the system's state. An object with five freely settable fields has five. If some
fields are derived from others by enforced rules, it has fewer, which makes it easier to predict
and control. Value objects and aggregates do exactly that: they **lock invariants inside** and
reduce the degrees of freedom. Since this pattern is for complex logic, it's mostly used in **core subdomains**.

## Check yourself

1. Are value objects data-only, behavior-only, immutable, or mutable?
2. What's the guiding principle for an aggregate's size?
3. Why commit only one aggregate per transaction?
4. Main difference between an active record and an aggregate?

<details><summary>Answers</summary>

1. Immutable, and they carry both data and behavior.
2. As small as possible while still keeping the data that must be strongly consistent together.
3. To force correct consistency and transaction boundaries.
4. An aggregate holds *all* of its logic. An active record's logic can live outside it.

</details>
