Syllabus Lesson 61 of 141 · Data models that bend
Data models that bend

Store events, not a balance

Why it matters A running total is the most natural way to model money, stock or points. It is also the model that cannot answer a single question about the past.

A small savings app needs a ledger. Today's request from the product owner is short: record deposits and withdrawals, and show each account's balance. In the same meeting they mention that the finance team "will want history" and that bank transfers sometimes arrive days late, dated in the past.

Event: a fact that happened, stored as it happened (account, amount, day). State, like a balance, can be worked out from events, but not the other way round.

Your turn

Today's request. Write new_ledger() (returns an empty ledger, any shape you like), record(ledger, account, amount, day) (amount in pence, negative for a withdrawal; day is a whole number) and balance(ledger, account).

What is coming. The business will ask about history. Hidden change requests, with data you have not seen, will call these, so write them now as well:

  • balance(ledger, account, on=day): the balance at the end of that day;
  • statement(ledger, account, start, end): a list of (day, amount) for entries with start <= day < end, by day, same-day entries in the order recorded.

Entries can be recorded late: an entry dated day 3 may arrive after day 20's. Unknown accounts have a balance of 0 and an empty statement.

Spotted a problem in this lesson? Report it · Ask about this lesson

This exercise opens soon

Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.