Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 61 ยท Projects

Project: Bank Account Model

Model a bank in Dart: a Money extension type, accounts with inheritance, sealed Result types for expected failures, exceptions for broken rules and records.

A bank account looks trivial until you list the rules: you cannot withdraw more than you have, you cannot deposit a negative amount, a transfer must never create or destroy money, and a savings account keeps a minimum balance. Each rule is a place where code can go wrong, which is exactly why a bank is a great object-oriented exercise.

In this project you build a small bank model in four stages and use a lot of what you have learned: classes, inheritance, enums, extension types, sealed classes, records and exceptions. The central question is how should a failure be reported? You will see two answers, a result value for expected business failures and an exception for rule violations that should never happen, and learn when to pick each.

The Dart code is read-only because Dart is not installed on the site. The TypeScript stand-ins have the same structure and run for real.

This is a teaching model, not banking software. Real systems add databases with transactions, audit logs, concurrency control and strict decimal rules. The ideas here (integer money, explicit failures, all-or-nothing transfers) are the real ones, though.

Stage 1: money without floating point

Never store money in a double: 0.1 + 0.2 is 0.30000000000000004. Store whole cents in an int. To stop cents from being mixed up with ordinary integers (a count, an id), wrap the int in an extension type. At run time it is just an int with no allocation, but at compile time Money and int are different types.

DART
extension type const Money(int cents) {
  static const zero = Money(0);

  Money operator +(Money other) => Money(cents + other.cents);
  Money operator -(Money other) => Money(cents - other.cents);
  bool operator >=(Money other) => cents >= other.cents;

  bool get isPositive => cents > 0;

  String format() {
    final sign = cents < 0 ? '-' : '';
    final abs = cents.abs();
    return '$sign\$${abs ~/ 100}.${(abs % 100).toString().padLeft(2, '0')}';
  }
}

Now Money(500) + Money(250) works, but Money(500) + 250 is a compile error, because the plain int is not a Money. The \$ in the format string is an escaped dollar sign, followed by an interpolation ${...}. The compiler will not let you forget to wrap or unwrap a value, which removes a whole class of unit mistakes.

Stage 2: results for expected failures

Think about what withdraw can do. It can succeed, or it can be refused (not enough money, a bad amount). A refusal is not a bug; customers ask for too much all the time. Reporting it with an exception forces every caller into try/catch and makes the normal path look exceptional.

Instead, return a sealed result:

DART
sealed class Result {
  const Result();
}

final class Ok extends Result {
  const Ok(this.balance);
  final Money balance;
}

final class Rejected extends Result {
  const Rejected(this.reason);
  final String reason;
}

Callers must look at the result, and an exhaustive switch guarantees they handle both cases:

DART
String describe(Result result) => switch (result) {
      Ok(:final balance) => 'ok, balance is ${balance.format()}',
      Rejected(:final reason) => 'rejected: $reason',
    };

Next comes the account itself. Every successful operation is recorded as an entry; a record is perfect for that, because an entry is just three named values and needs no class of its own.

DART
enum TxKind { deposit, withdrawal, interest, transferIn, transferOut }

typedef Entry = ({TxKind kind, Money amount, Money balanceAfter});

class Account {
  Account(this.owner, {Money opening = Money.zero}) : _balance = opening;

  final String owner;
  Money _balance;
  final List<Entry> _entries = [];

  Money get balance => _balance;
  List<Entry> get entries => List.unmodifiable(_entries);

  /// The amount that must always stay in the account.
  Money get minimumBalance => Money.zero;

  Result deposit(Money amount, {TxKind kind = TxKind.deposit}) {
    if (!amount.isPositive) return const Rejected('amount must be positive');
    _balance = _balance + amount;
    _entries.add((kind: kind, amount: amount, balanceAfter: _balance));
    return Ok(_balance);
  }

  Result withdraw(Money amount, {TxKind kind = TxKind.withdrawal}) {
    if (!amount.isPositive) return const Rejected('amount must be positive');
    final spendable = _balance - minimumBalance;
    if (!(spendable >= amount)) {
      return Rejected('only ${spendable.format()} available');
    }
    _balance = _balance - amount;
    _entries.add((kind: kind, amount: amount, balanceAfter: _balance));
    return Ok(_balance);
  }
}

Three design choices are worth pausing on. The balance field is private, so the only ways to change it are deposit and withdraw, and both check their rules. The entries getter returns an unmodifiable copy, so outside code cannot rewrite history. And minimumBalance is a getter that subclasses can override, which is how the savings account will differ without duplicating any logic.

classDiagram
    class Account {
      -Money _balance
      +Money balance
      +Money minimumBalance
      +deposit(Money) Result
      +withdraw(Money) Result
    }
    class SavingsAccount {
      +Money minimumBalance
      +addInterest(int) Result
    }
    class Result {
      <<sealed>>
    }
    Account <|-- SavingsAccount
    Result <|-- Ok
    Result <|-- Rejected
    Account ..> Result : returns

Savings accounts reuse the checks in Account; both operations return a sealed Result.

Here is the first stand-in. TypeScript has no extension types or sealed classes, so Money is a small class and Result is a discriminated union, which gives the same compile-time guarantees.

TypeScript Stages 1-2: Money, Result and an Account (stand-in)

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 node:readline or readFileSync(0)), it gets the next line from this box.

Stage 3: inheritance and transfers

A savings account is an account with a rule changed (a minimum balance) and one new feature (interest). Inheritance fits: override one getter, add one method.

DART
class SavingsAccount extends Account {
  SavingsAccount(super.owner, {super.opening});

  @override
  Money get minimumBalance => const Money(1000); // $10.00 must stay

  /// Adds interest; [basisPoints] 250 means 2.50 percent.
  Result addInterest(int basisPoints) {
    final interest = Money(balance.cents * basisPoints ~/ 10000);
    return deposit(interest, kind: TxKind.interest);
  }
}

Interest uses integer division ~/, so fractions of a cent are dropped (a real bank must decide a rounding rule and write it down). If the interest rounds to zero, deposit rejects it, and the caller sees that in the result.

A transfer moves money between two accounts. The golden rule: it must be all-or-nothing. Do the step that can fail first (the withdrawal), and only if it succeeds do the step that cannot fail (the deposit of the same, already validated, amount).

DART
Result transfer(Account from, Account to, Money amount) {
  if (identical(from, to)) {
    return const Rejected('cannot transfer to the same account');
  }
  final out = from.withdraw(amount, kind: TxKind.transferOut);
  if (out is Rejected) return out;

  final into = to.deposit(amount, kind: TxKind.transferIn);
  if (into is Rejected) {
    // Unreachable: the amount was already validated by withdraw.
    throw StateError('deposit failed after withdrawal: ${into.reason}');
  }
  return out;
}

Notice the final throw. This is the second answer to "how do I report a failure": the situation cannot happen unless the code has a bug, so an exception is the right tool, and it is a StateError (an Error, not an Exception) because nobody should try to recover from it.

Stage 4: statements and exceptions

A statement turns the entries into text. Because each entry is a record, a pattern pulls the fields apart:

DART
List<String> statement(Account account) => [
      for (final (:kind, :amount, :balanceAfter) in account.entries)
        '${kind.name.padRight(12)}${amount.format().padLeft(10)}${balanceAfter.format().padLeft(10)}',
    ];

Some callers do not want to inspect a Result: a script that must either withdraw or stop. Give them an opt-in throwing version without touching Account, using an extension and a custom exception:

DART
class BankException implements Exception {
  const BankException(this.message);
  final String message;

  @override
  String toString() => 'BankException: $message';
}

extension WithdrawOrThrow on Account {
  Money withdrawOrThrow(Money amount) => switch (withdraw(amount)) {
        Ok(:final balance) => balance,
        Rejected(:final reason) => throw BankException(reason),
      };
}

A good rule of thumb: use a result when the failure is an expected outcome the caller should decide about (insufficient funds, invalid input from a user). Use an exception when a precondition was broken or something is truly exceptional (a bug, a missing file, a network failure). Providing both, as here, costs one small extension.

The complete stand-in follows. It adds the savings account, the transfer, the statement and the exception wrapper, then runs a conservation test: after 300 pseudo-random transfers between three accounts, the total amount of money must be exactly what we started with and no account may be below its minimum. Invariant checks like this catch bugs that hand-picked examples miss.

TypeScript Stages 3-4: savings, transfers, statement and invariant test (stand-in)

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 node:readline or readFileSync(0)), it gets the next line from this box.

Ideas to extend it

  • Add a Bank class that holds accounts by id in a Map and exposes transfer(fromId, toId, amount), returning a Rejected result for an unknown id.
  • Replace the String reason with a sealed Reason hierarchy (InsufficientFunds(available), InvalidAmount) so callers can react to each case without parsing text.
  • Add an overdraft limit by overriding minimumBalance with a negative value in a CheckingAccount.
  • Make operations asynchronous with a fake database and Future (see futures), and think about what happens if two transfers touch the same account at once.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is money stored as an int number of cents rather than a double?

    Binary floating point cannot represent most decimal fractions exactly. Integer cents are exact.
  2. 2. What does making Money an extension type add compared with a plain int?

    An extension type wraps its representation with no run-time cost, but the compiler treats it as a separate type with its own operations.
  3. 3. When is a sealed Result better than an exception?

    Insufficient funds happens in normal use. A result forces callers to handle it, and a switch over the sealed type checks they covered every case.
  4. 4. Why does transfer do the withdrawal first and the deposit second?

    If the withdrawal is refused nothing has changed. Once it succeeds, the deposit of the validated amount cannot fail, so the transfer is all-or-nothing.

Summary

  • Wrap raw numbers in an extension type (Money) to get type safety at zero run-time cost, and keep money in integer cents.
  • Return a sealed Result for expected failures; use exceptions for broken preconditions and impossible states.
  • Keep state private, change it only through methods that enforce the rules, and expose history as an unmodifiable list of records.
  • Override a small hook (minimumBalance) so subclasses change rules without duplicating logic.
  • Check invariants, such as "total money is conserved", with a test that runs many random operations.

Next: Project: Expression Evaluator.