Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: A Bank Account Simulator in D

Build a bank account simulator in D with classes, interfaces, contracts, exceptions and unit tests, plus a runnable C version with a transaction log and state machine.

This project ties the chapter together: classes with inheritance, contracts that guard invariants, exceptions for run-time failures, and tests. You build a small bank with accounts, deposits, withdrawals, transfers and a transaction log. The D design is read-only on this site; the C program that follows is a complete runnable version of the same rules, including a state machine for account status.

Requirements

  1. An account has an id, an owner, a balance in cents (integers, never floating point for money) and a status.
  2. Deposits and withdrawals must be positive. Withdrawals must not exceed the balance (a checking account may go negative up to an overdraft limit).
  3. A transfer moves money between two accounts atomically: either both sides change or neither.
  4. Frozen accounts reject every operation.
  5. Every successful operation appends a line to a log.
stateDiagram-v2
    [*] --> Active
    Active --> Frozen: freeze
    Frozen --> Active: unfreeze
    Active --> Closed: close (balance 0)
    Closed --> [*]

The status of an account is a small state machine.

The design in D

D
import std.exception : enforce;
import std.format : format;

enum Status { active, frozen, closed }

class InsufficientFunds : Exception
{
    this(long needed, long available)
    {
        super(format("need %s cents but only %s available", needed, available));
    }
}

abstract class Account
{
    protected long cents;
    protected Status status = Status.active;
    const int id;
    const string owner;
    string[]* log;                       // shared transaction log

    this(int id, string owner, string[]* log)
    {
        this.id = id; this.owner = owner; this.log = log;
    }

    invariant { assert(status != Status.closed || cents == 0); }

    abstract long availableToWithdraw() const;

    final void deposit(long amount)
    in (amount > 0, "deposit must be positive")
    {
        enforce(status == Status.active, "account not active");
        cents += amount;
        *log ~= format("deposit %s to #%s", amount, id);
    }

    final void withdraw(long amount)
    in (amount > 0)
    {
        enforce(status == Status.active, "account not active");
        if (amount > availableToWithdraw())
            throw new InsufficientFunds(amount, availableToWithdraw());
        cents -= amount;
        *log ~= format("withdraw %s from #%s", amount, id);
    }

    long balance() const { return cents; }
}

class Savings : Account
{
    this(int id, string owner, string[]* log) { super(id, owner, log); }
    override long availableToWithdraw() const { return cents; }
}

class Checking : Account
{
    private long overdraft;
    this(int id, string owner, string[]* log, long overdraft)
    {
        super(id, owner, log);
        this.overdraft = overdraft;
    }
    override long availableToWithdraw() const { return cents + overdraft; }
}

The abstract base holds the shared rules; each subclass answers one question differently: how much may leave the account. The final on deposit and withdraw stops subclasses from weakening the rules. See classes and inheritance if any keyword is unfamiliar.

The atomic transfer

D
void transfer(Account from, Account to, long amount)
{
    from.withdraw(amount);          // may throw: nothing has changed yet
    try
    {
        to.deposit(amount);         // may throw: undo the withdrawal
    }
    catch (Exception e)
    {
        from.deposit(amount);       // compensating action
        throw e;
    }
}

Withdrawing first means a failure leaves everything as it was. If the deposit fails, a compensating deposit restores the first account. In a database you would use a transaction, but the idea is the same. You could also write this with scope(failure), as in scope and RAII.

Tests

D
unittest
{
    string[] log;
    auto a = new Savings(1, "Mina", &log);
    auto b = new Checking(2, "Omar", &log, 5_000);

    a.deposit(10_000);
    transfer(a, b, 4_000);
    assert(a.balance == 6_000 && b.balance == 4_000);

    b.withdraw(8_000);                  // dips into the overdraft
    assert(b.balance == -4_000);

    import std.exception : assertThrown;
    assertThrown!InsufficientFunds(a.withdraw(100_000));
    assertThrown!Exception(b.withdraw(2_000));   // overdraft exhausted
    assert(log.length == 4);
}

The runnable C version

C has no classes, so the program uses a struct with a function pointer for "how much may leave" (the abstract method) and an enum for the status. The rules, the transfer with compensation and the log are the same.

C Bank simulator: accounts, transfers and a log

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Read the output against the D unit test: the same numbers appear, and the failed transfer to the frozen account is rolled back and logged.

Extensions

  • Interest: add a Savings.addInterest(rate) that uses integer math with rounding rules, and test it.
  • Persistence: serialize accounts to JSON with std.json and reload them.
  • Concurrency: wrap each account in a synchronized class, then discover why transfers need a lock order (always lock the lower id first) to avoid deadlock. See message passing for the actor alternative: one thread owns the bank and everyone else sends it requests.
  • Statement: print a monthly statement from the log using ranges (filter, map).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store money as integer cents?

    Rounding errors in floating point add up; integers are exact.
  2. 2. What makes Savings and Checking differ in this design?

    The abstract method is the single point of variation; the shared rules stay final.
  3. 3. What does the compensating action in transfer accomplish?

    It makes the transfer all-or-nothing.
  4. 4. Which tool states that a closed account must have zero balance?

    Invariants express conditions that must hold between method calls.

Summary

  • An abstract base with final operations and one abstract rule gives a safe class hierarchy.
  • Contracts and invariants protect assumptions; exceptions report run-time failures.
  • Transfers are made all-or-nothing by ordering operations and compensating on failure.
  • A small state machine and a log make behavior observable and testable.

Next: Practice Problems