Syllabus Lesson 138 of 141 · Ten doors and the field kit
Ten doors and the field kit

Door 2: a ledger that survives its users

Why it matters Real data models fail in two ways: the next change request does not fit, or a caller uses the API wrongly and the data quietly breaks. This door tests both.

A small company wants an internal ledger: accounts for teams, money moved between them, and deposits from outside. You get the first spec, two change requests that have already been agreed, and the misuse script that the test team will run against it. All of it is below and in the exercise.

Change requests

  • CR1: finance needs the balance of any account at any past time.
  • CR2: teams get renamed. A renamed account keeps its id, balance and history; its old name becomes free.

The misuse script

Each of these must raise ValueError and change nothing: an amount that is not a positive whole number of cents (0, -5, 2.5, 2.0, True, "10"); an unknown account; sending to the same account; a transfer that would take the sender below 0; a transfer id already used with different details; opening an account with a name in use. Callers also retry on timeouts: the same transfer id with the same details again must do nothing, quietly. A retry arrives later than the first try, so its time may differ: the details that must match are the two accounts and the amount.

Your turn

Write six functions over a ledger you design (plain data or an object):

  • new_ledger(): an empty ledger.
  • open_account(ledger, name): returns a new account id (any value you like). New accounts start at 0.
  • rename(ledger, account_id, new_name): CR2.
  • find(ledger, name): the id of the account now called name, or ValueError.
  • transfer(ledger, transfer_id, from_id, to_id, cents, t): moves cents at time t; from_id None means a deposit from outside. Times never go down.
  • balance(ledger, account_id, t=None): the balance counting transfers with time <= t, or all of them if t is None (CR1).
Every case in the misuse script raises ValueError and changes nothing. A retry (same transfer id, same accounts and amount, any later time) does nothing and raises nothing.

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.