# Implementing Simple Business Logic
> **In one sentence:** when the logic is simple, use a simple pattern, but get the transactional
> behavior exactly right, because that's where "simple" code usually breaks.

Business logic is the reason the software exists. A beautiful UI on top of logic that doesn't
serve the business is just an expensive demo. This chapter covers the two patterns for the easy
end of the spectrum, which fits supporting subdomains.

## Transaction script

**Idea:** organize the logic as a set of procedures, **one per operation** the system exposes
("register member", "cancel booking", "export invoices"). Each procedure is a straightforward
script. It can use a thin data-access helper or talk to the database directly.

**The one non-negotiable rule:** each script must behave like a transaction. It either fully
succeeds or leaves no trace. If it fails halfway, the system must not be left in a half-updated
state, so roll back or run a compensating action.

```python
def redeem_voucher(db, voucher_code, order_id):
    with db.transaction():                 # all or nothing
        voucher = db.fetch_voucher(voucher_code)
        if voucher.used:
            raise AlreadyRedeemed()
        db.mark_voucher_used(voucher_code)
        db.apply_discount(order_id, voucher.amount)
```

### Where it goes wrong

It looks trivial, yet broken transactional behavior is behind many real data-corruption bugs.
Three classic traps:

1. **No transaction around several writes.** Two updates run separately, and a crash between
   them leaves only the first one applied. *Fix:* wrap them in one database transaction.
2. **Database plus message bus.** You update a row, then publish a message. If the process dies in
   between, the database changed but nobody was told. A distributed transaction across both is
   complex and rarely worth it. *Fix:* use patterns from later chapters (the **outbox** in
   Chapter 9, or **CQRS** projections in Chapter 8).
3. **The hidden distributed transaction: the caller.** Even a single-row update such as
   `points = points + 10` is risky. If the update succeeds but the reply to the caller is lost
   (network blip, crash), the caller retries and the points are added twice. *Fixes:*
   - Make the operation **idempotent**: the caller sends the target value (`points = 120`), so
     repeating it changes nothing.
   - Or use **optimistic concurrency**: only apply the change if the value is still what the
     caller saw (`... WHERE points = 110`).

### When to use it

- Simple, procedural logic such as ETL jobs (extract, transform, load).
- **Supporting subdomains**, and adapters for integrating generic subdomains or building an
  anticorruption layer.
- **Never for core subdomains.** As logic grows, rules get copied across scripts, the copies
  drift apart, and you end up with a big ball of mud.

Its strength and its weakness are the same thing: very little abstraction. And every other
business-logic pattern still has a transaction script inside it somewhere.

## Active record

**Idea:** the logic is still simple, but the **data structures aren't**: nested objects,
one-to-many and many-to-many relations. Mapping those by hand in every script means a lot of
repeated code. So each structure becomes an **active record**, an object that holds the data
*and* knows how to load and save itself (CRUD), usually through an ORM.

```python
def create_member(details):
    with db.transaction():
        member = Member()              # active record
        member.name = details.name
        member.email = details.email
        member.save()                  # the object persists itself
```

- The procedures are still transaction scripts. They just work with active records instead of raw tables.
- Active records may contain light logic such as validating fields, but their data is usually
  open (public getters and setters), so **behavior and data stay separate**. Code outside the
  object changes its state.
- Fits supporting subdomains, integrations and model transformations.
- It's sometimes called an "anemic domain model" antipattern. A fairer view is that it's a tool:
  fine for simple logic, harmful for complex logic. Using a heavier pattern for simple logic
  causes harm too, through needless complexity.

*(This is the design pattern, not any specific framework that took the name.)*

## Being pragmatic

Data integrity matters, but not every corner needs gold plating. At very large scale, ask the
business whether losing or duplicating a tiny fraction of records (say, telemetry pings) actually
hurts. Sometimes cutting corners is the right call, as long as you judged the risk deliberately.

## Check yourself

1. Can transaction script or active record implement a core subdomain?
2. Which of them fits a supporting subdomain?
3. A function picks the least-busy courier, increments their job counter, saves a new delivery
   assigned to them, then sends a push notification, all with no transaction. Name three ways the
   data can end up wrong.

<details><summary>Answers</summary>

1. No.
2. Both.
3. The counter goes up but no delivery is saved; the delivery is saved but the notification never
   goes out; a retry after a lost reply bumps the counter twice. There are more, such as two
   requests racing for the same courier.

</details>
