Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 ยท Projects and Practice

Project: Bank Accounts

Design a bank account system in Object Pascal with a base class, savings and checking descendants, custom exceptions and safe transfers, plus a runnable C model with a virtual table.

The contact book used records and units. This project uses the object-oriented features of the chapter: a base class, descendants that change behavior through virtual and override, properties that guard the balance, and exceptions for errors. It also shows a classic pattern: a transfer that never loses money, even when something fails halfway.

Pascal compilers cannot run in the browser, so the Pascal code is read-only. A complete C program with the same structure runs below, so you can change rules and watch the results.

Requirements

  • Every account has an owner and a balance (in Currency, a fixed-point type that avoids floating-point rounding errors with money).
  • Deposit and Withdraw change the balance. Amounts must be positive.
  • A checking account may go into an overdraft up to a limit.
  • A savings account can never go below zero and can add interest.
  • A Transfer moves money between two accounts; if either step fails, nothing changes.
  • Errors are reported with exceptions that carry useful information.

The exception classes

Start with the errors, because they define the vocabulary (see interfaces and exceptions):

PASCAL
type
  EBankError = class(Exception);

  EInvalidAmount = class(EBankError);

  EInsufficientFunds = class(EBankError)
  strict private
    FShortBy: Currency;
  public
    constructor Create(AShortBy: Currency);
    property ShortBy: Currency read FShortBy;
  end;

constructor EInsufficientFunds.Create(AShortBy: Currency);
begin
  inherited CreateFmt('Not enough money: short by %m', [AShortBy]);
  FShortBy := AShortBy;
end;

All bank errors descend from EBankError, so a caller can catch just bank problems with one handler and let unrelated bugs travel on.

The base class

PASCAL
type
  TAccount = class
  strict private
    FOwner: string;
    FBalance: Currency;
  strict protected
    procedure SetBalance(const Value: Currency);
    function MinimumBalance: Currency; virtual;
  public
    constructor Create(const AOwner: string; AInitial: Currency = 0);
    procedure Deposit(Amount: Currency);
    procedure Withdraw(Amount: Currency); virtual;
    function Describe: string; virtual;
    property Owner: string read FOwner;
    property Balance: Currency read FBalance;
  end;

constructor TAccount.Create(const AOwner: string; AInitial: Currency);
begin
  inherited Create;
  FOwner := AOwner;
  FBalance := AInitial;
end;

function TAccount.MinimumBalance: Currency;
begin
  Result := 0;                       // the default: no overdraft
end;

procedure TAccount.SetBalance(const Value: Currency);
begin
  FBalance := Value;
end;

procedure TAccount.Deposit(Amount: Currency);
begin
  if Amount <= 0 then
    raise EInvalidAmount.Create('Deposit must be positive');
  FBalance := FBalance + Amount;
end;

procedure TAccount.Withdraw(Amount: Currency);
begin
  if Amount <= 0 then
    raise EInvalidAmount.Create('Withdrawal must be positive');
  if FBalance - Amount < MinimumBalance then
    raise EInsufficientFunds.Create(MinimumBalance - (FBalance - Amount));
  FBalance := FBalance - Amount;
end;

function TAccount.Describe: string;
begin
  Result := Format('%s: %m', [FOwner, FBalance]);
end;

The balance is a read-only property: nobody outside can assign to it. The one rule about how low the balance can go lives in a single virtual method, MinimumBalance, so descendants customize the rule without rewriting Withdraw. That is the template method pattern: a fixed algorithm with a replaceable step.

The descendants

PASCAL
type
  TCheckingAccount = class(TAccount)
  strict private
    FOverdraftLimit: Currency;
  strict protected
    function MinimumBalance: Currency; override;
  public
    constructor Create(const AOwner: string; AInitial, AOverdraft: Currency);
  end;

  TSavingsAccount = class(TAccount)
  strict private
    FRate: Double;
  public
    constructor Create(const AOwner: string; AInitial: Currency; ARate: Double);
    procedure AddInterest;
    function Describe: string; override;
  end;

function TCheckingAccount.MinimumBalance: Currency;
begin
  Result := -FOverdraftLimit;
end;

procedure TSavingsAccount.AddInterest;
begin
  Deposit(Balance * FRate);          // reuses the validated Deposit
end;

function TSavingsAccount.Describe: string;
begin
  Result := inherited Describe + Format(' (savings, %.1f%%)', [FRate * 100]);
end;

TCheckingAccount only overrides one rule. TSavingsAccount extends Describe by calling inherited and appending text. Code that holds a TAccount never needs to know which kind it has.

A safe transfer

PASCAL
procedure Transfer(Source, Target: TAccount; Amount: Currency);
begin
  Source.Withdraw(Amount);          // may raise: then nothing has changed yet
  try
    Target.Deposit(Amount);
  except
    Source.Deposit(Amount);         // undo the withdrawal
    raise;
  end;
end;

The order matters. The withdrawal can fail for lack of money, and then nothing has happened. If the deposit fails afterwards, the except block puts the money back and re-raises the exception. Real systems use database transactions for this (databases with FireDAC), but the idea is identical: all or nothing.

Using it, with ownership handled by a list:

PASCAL
var
  Accounts: TObjectList<TAccount>;
begin
  Accounts := TObjectList<TAccount>.Create;   // owns its accounts
  try
    Accounts.Add(TCheckingAccount.Create('Ada', 100, 50));
    Accounts.Add(TSavingsAccount.Create('Linus', 500, 0.02));
    try
      Transfer(Accounts[0], Accounts[1], 120);   // overdraft allowed
      Transfer(Accounts[1], Accounts[0], 1000);  // too much
    except
      on E: EInsufficientFunds do
        WriteLn('Transfer refused: ', E.Message);
      on E: EBankError do
        WriteLn('Bank error: ', E.Message);
    end;
    for var A in Accounts do
      WriteLn(A.Describe);
  finally
    Accounts.Free;
  end;
end;

The model in C

C has no exceptions, so the program reports failures with return codes, and uses a virtual table for the minimum balance and the description. The output shows an allowed overdraft, a refused transfer and interest. Amounts are in cents (integers) to avoid rounding problems, the same reason Pascal offers Currency.

C Stand-in: accounts, overdraft, savings and a safe transfer

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.

Check the second line of output: the failed transfer left both balances untouched. Then, with Ada at -20.00, a 40.00 withdrawal would pass her 50.00 overdraft limit, so it is refused.

Ideas for extending it

  1. Add a transaction history: a TList<TTransaction> inside each account, filled by Deposit and Withdraw, with a Statement method.
  2. Add OnLowBalance event to TAccount (see events and the IDE).
  3. Define an IAccount interface and a TBank class that finds accounts by number.
  4. Write unit tests for every rule: deposits of zero, withdrawing exactly the limit, a failing transfer.
  5. Persist accounts in SQLite and make Transfer a real transaction.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is MinimumBalance a virtual method instead of Withdraw being rewritten in each descendant?

    Isolating the part that varies keeps shared logic in one place and avoids duplicated bugs.
  2. 2. Why use Currency instead of Double for money?

    Floating-point numbers cannot represent most decimal fractions exactly. Currency stores scaled integers.
  3. 3. In Transfer, what does the except block with a bare raise; do?

    Cleanup in except, followed by raise, keeps the data consistent without swallowing the error.
  4. 4. What is the benefit of having all bank errors descend from EBankError?

    A shared base class lets callers choose how broad their handler is.

Summary

  • A base class holds the common algorithm; a virtual method isolates the rule that differs (the template method pattern).
  • Descendants override only what changes and call inherited to extend behavior.
  • Read-only properties protect the balance; custom exceptions carry details.
  • A transfer is all-or-nothing: withdraw first, undo on failure, re-raise.
  • Use Currency for money, and a TObjectList to own the accounts.

Next: Project: Text Adventure Engine