Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: Bank Accounts with CLOS, Conditions and Restarts

Build a bank account system in Common Lisp that combines CLOS classes, generic functions, method combination, custom conditions and restarts, with a runnable JavaScript model.

This project pulls the chapter together: CLOS for the data model and behavior, method combination for cross-cutting concerns, conditions for failures and restarts for recovery. You will design a small banking core and see how each Lisp feature carries a piece of the design.

No Common Lisp implementation runs on this site, so the Lisp code is read-only. The JavaScript model in each step follows the same structure so you can run and alter it. It is a stand-in, not Lisp.

Requirements

  • Accounts have an owner, a balance and a history of transactions.
  • Kinds: checking (can overdraw up to a limit) and savings (earns interest, no overdraft).
  • deposit, withdraw, transfer and monthly-update operations.
  • Invalid amounts and insufficient funds signal conditions.
  • Policy decisions (retry with a smaller amount, skip, abort) live outside the account code, via restarts.
  • Every operation is logged without editing the core methods.

Step 1: classes

LISP
(defclass account ()
  ((owner   :initarg :owner :reader owner)
   (balance :initarg :balance :initform 0 :accessor balance)
   (history :initform nil :accessor history)))

(defclass checking (account)
  ((overdraft :initarg :overdraft :initform 100 :reader overdraft)))

(defclass savings (account)
  ((rate :initarg :rate :initform 0.02 :reader rate)))

history has its own list per instance because the :initform is evaluated per instance (see classes and instances). A shared mutable default would be a bug.

Step 2: conditions

LISP
(define-condition bank-error (error)
  ((account :initarg :account :reader error-account)))

(define-condition invalid-amount (bank-error)
  ((amount :initarg :amount :reader amount))
  (:report (lambda (c s) (format s "Invalid amount: ~a" (amount c)))))

(define-condition insufficient-funds (bank-error)
  ((needed :initarg :needed :reader needed)
   (available :initarg :available :reader available))
  (:report (lambda (c s)
             (format s "Need ~a, only ~a available" (needed c) (available c)))))

A tiny hierarchy (bank-error as the root) lets callers catch broadly or narrowly, as discussed in the conditions lesson.

Step 3: generic functions

LISP
(defgeneric available-funds (account)
  (:documentation "Amount that can be withdrawn right now."))
(defmethod available-funds ((a account)) (balance a))
(defmethod available-funds ((a checking)) (+ (balance a) (overdraft a)))

(defgeneric deposit (account amount))
(defmethod deposit ((a account) amount)
  (incf (balance a) amount)
  (push (list :deposit amount) (history a))
  (balance a))

(defgeneric withdraw (account amount))
(defmethod withdraw ((a account) amount)
  (when (> amount (available-funds a))
    (restart-case
        (error 'insufficient-funds :account a :needed amount
                                   :available (available-funds a))
      (withdraw-available ()
        :report "Withdraw everything that is available instead."
        (return-from withdraw (withdraw a (available-funds a))))
      (skip-withdrawal ()
        :report "Skip this withdrawal."
        (return-from withdraw nil))))
  (decf (balance a) amount)
  (push (list :withdraw amount) (history a))
  (balance a))

The account knows how to recover (two restarts); it does not decide. available-funds is specialized on checking to include the overdraft limit, so withdraw itself has no typecase.

Step 4: validation and logging with auxiliary methods

Validation and logging apply to every kind of account, so they go in :before and :around methods (method combination):

LISP
(defmethod deposit :before ((a account) amount)
  (unless (and (realp amount) (plusp amount))
    (error 'invalid-amount :account a :amount amount)))

(defmethod withdraw :before ((a account) amount)
  (unless (and (realp amount) (plusp amount))
    (error 'invalid-amount :account a :amount amount)))

(defmethod withdraw :around ((a account) amount)
  (format t "[log] ~a withdraws ~a~%" (owner a) amount)
  (call-next-method))

Putting validation in :before keeps the primary methods short, and a new account class inherits it automatically.

Step 5: interest, transfer and policy

LISP
(defgeneric monthly-update (account))
(defmethod monthly-update ((a account)) nil)
(defmethod monthly-update ((a savings))
  (deposit a (* (balance a) (/ (rate a) 12))))

(defun transfer (from to amount)
  (withdraw from amount)
  (deposit to amount))

;; Policy lives at the call site:
(handler-bind ((insufficient-funds
                 (lambda (c)
                   (declare (ignore c))
                   (invoke-restart 'withdraw-available))))
  (transfer *alice* *bob* 1000))

The batch-processing code decides to take "whatever is available" using invoke-restart; another caller might choose skip-withdrawal or let the error reach the user. transfer has a flaw worth fixing as an exercise: if deposit fails after withdraw succeeded, money vanishes. Wrap the pair so that failure restores the balance with unwind-protect or by recording and reversing the first step.

JS Stand-in: accounts, validation, restarts

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

No output.

Alice's balance after withdraw-available is -100: she had 300, the overdraft allows 400 total, and the restart took everything available.

Testing it

Use the mini framework from the last project or FiveAM:

LISP
(deftest test-withdraw
  (let ((a (make-instance 'checking :owner "t" :balance 50 :overdraft 100)))
    (check (= 20 (withdraw a 30))
           (= -100 (withdraw a 120)))))

(deftest test-invalid
  (check-signals invalid-amount
    (deposit (make-instance 'account :owner "t") -1)))

Extensions

  • A print-object method so accounts print as #<CHECKING alice 300>.
  • A statement generic function with :around formatting and a with-output-to-string helper.
  • Persistence using closer-mop to list slots generically and write them as s-expressions.
  • An audited mixin with :after methods that append to a log.
  • Thread safety: a lock slot and bordeaux-threads:with-lock-held inside withdraw.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should validation of the amount live in this design, and why?

    :before methods run for any subclass and keep the primary methods focused.
  2. 2. Why do withdraw-available and skip-withdrawal exist as restarts inside withdraw?

    That separates mechanism (in the account) from policy (in the batch code).
  3. 3. Why is available-funds a generic function specialized on checking?

    Dispatch on the account class replaces explicit type tests, and new kinds extend it by adding methods.
  4. 4. What bug does the simple transfer function have?

    The two steps are not atomic; compensate or use unwind-protect to restore the balance.

Summary

  • Classes model the data; generic functions with specialization remove type tests.
  • :before and :around methods add validation and logging for every subclass.
  • Conditions describe failures; restarts inside withdraw offer recovery; handlers at the call site choose.
  • Transfers need atomicity thinking: plan compensation for partial failure.
  • The JavaScript model shows the structure, but real CLOS dispatch and restarts are richer.

Next: Practice: Common Lisp Exercises and Idioms