progress

~/problems / Simulation & OOP design / Object-oriented design and extensible simulations

A bank account class with invariants

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Design rounds often start like this: a small class whose state can never become invalid. Here, a balance never goes negative, and a failed operation changes nothing.

Implement class Account:

  • Account(owner, balance=0): an owner's name and a starting balance in cents.
  • deposit(amount), withdraw(amount), and transfer(other, amount) (moves money into the Account other).
  • balance(): the current balance.
  • history(): this account's successful operations, oldest first, as (kind, amount) with kind one of "deposit", "withdraw", "transfer_out", "transfer_in".

Raise ValueError if amount isn't a positive integer, the balance is too small to withdraw or transfer, other is the same account, or the starting balance is negative. When a call raises, neither account changes.

a = Account("ann", 100)
b = Account("bob")
a.deposit(50)
a.transfer(b, 120)
a.balance(), b.balance()   # (30, 120)
a.history()                # [("deposit", 50), ("transfer_out", 120)]
b.history()                # [("transfer_in", 120)]
a.withdraw(31)             # ValueError: insufficient funds; a.balance() is still 30

Give each account its own history list (beware mutable defaults), and return a copy from history().

Show hint

validate first, mutate last.

Topic: Object-oriented design and extensible simulations. Classes that survive new requirements: games, payments, subscriptions, refactors.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc