Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 134 ยท Projects

Project: Bank Account Simulation

Build a bank account simulation in Ruby step by step: classes, custom exceptions, a mixin audit log, Comparable accounts, transfers and a scripted command loop.

Bank accounts are a classic practice project because the rules are easy to state and easy to get wrong. You may not withdraw more than you have. You may not deposit a negative amount. A transfer must either happen completely or not at all. Every change must leave a trace. These rules give us a reason to use almost everything from the object-oriented chapters: classes, custom exceptions, modules as mixins, Comparable and a little pattern matching.

We will build the program in small steps, run each step, and finish with a complete program that reads scripted commands from standard input. Money is kept as whole dollars (integers) to keep the focus on design. Real systems store the smallest currency unit (cents) as an integer, or use BigDecimal, because Float cannot represent amounts like 0.10 exactly.

Step 1: a naive account

Start with the simplest thing that could work: an object that holds an owner and a balance, with two methods that change it.

Ruby Step 1: a naive Account

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 gets), it gets the next line from this box.

Returning self from both methods lets us chain calls, which is why deposit(50).withdraw(30) works. The result is what you would hope for in the first case (120). The next two lines show the problem: the account happily goes to -380 and then to -1380, and a "deposit" of -1000 quietly takes money out. Nothing in the code states what a valid account looks like. We fix that with exceptions.

Step 2: errors that say what went wrong

Raising a plain RuntimeError with a string works, but callers then have to match on message text. Custom exception classes let a caller say which problem happened with rescue. We put them in a Bank module, which doubles as a namespace, and give them a shared parent so that rescue Bank::Error catches the whole family.

Ruby Step 2: custom exceptions guard the rules

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 gets), it gets the next line from this box.

Several details are worth a second look. The exceptions build their own message by calling super with a string, so the places that raise them stay short: raise InvalidAmount.new(amount). InsufficientFunds also stores needed and available as data, so a caller can compute the shortfall instead of parsing text. The rescue clauses are tried top to bottom, and the more specific class comes first; had we put Bank::Error first, it would catch everything and the second clause would never run.

The method names ending in ! follow a Ruby convention: check_amount! raises instead of returning a status. Because the check lives in one private method, deposit and withdraw cannot disagree about what a valid amount is. After the loop the balance is still 100, which tells us that no failed call changed the account. That is a design rule worth stating: validate first, change state last.

What an uncaught error looks like

If nobody rescues the exception, the program stops and Ruby prints the class, message and a backtrace. This is what the same mistake looks like without the safety net.

Ruby An unhandled InsufficientFunds (fails on purpose)

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 gets), it gets the next line from this box.

The first line of the output is main.rb:14:in 'Bank::Account#withdraw': need 500 but only 80 available (Bank::InsufficientFunds). It names the file and line, the method (with its class), the message and the exception class in parentheses. The lines that follow show who called whom. Reading the first line first is usually enough.

Step 3: accounts that can be compared

A bank report wants to know who has the most money. Ruby's Comparable module turns one method, <=>, into <, >, between?, clamp, min, max support and sorting. We compare accounts by balance and add a to_s for readable output.

Ruby Step 3: Comparable accounts

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 gets), it gets the next line from this box.

Notice the third line of output: ada == linus is true because Comparable#== uses <=>, and both balances are 900, while equal? still says they are two different objects. For accounts this may or may not be what you want (two customers are not the same account just because they hold the same amount). If it bothers you, define == yourself; see Equality and Identity. Sorting with equal balances keeps no promised order, so sort.map(&:owner) shows a valid order, not the only one.

Step 4: an audit log as a mixin

Every change to an account should leave a trace: what happened, how much, and the balance afterwards. Logging is a separate concern from banking, which makes it a good candidate for a module. Any class can include it and gain audit_log and a private record method.

Ruby Step 4: the Audited mixin

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 gets), it gets the next line from this box.

The hash shorthand { kind:, amount:, balance: @balance } fills the keys from variables with the same names. The ||= idiom creates the array lazily on first use, so the module needs no initialize of its own (modules that define initialize easily clash with the class using them). Because record is private, the outside world can read the log but never write to it, which is the whole point of an audit trail.

The last two lines show how the mixin sits in the class hierarchy: Account.ancestors lists Account, then Audited, then Object. When Ruby looks for a method, it walks that list in order. The final check, that the log reproduces the balance, is a nice property: the log is the account's history, and the balance is derived from it. In event-sourced systems that idea becomes the main design.

Step 5: the complete program

Now we combine everything and add the missing piece: a Branch that holds many accounts and implements open and transfer. A transfer is two operations, and the rule is that either both happen or neither does. Because withdraw validates before it changes anything, we can do the withdrawal first; if it raises, the destination was never touched. We also check the destination exists before starting.

The program reads commands from standard input. In a real terminal you would type them; here the editor presets them with input. Each command is matched with case/in against the shape of the split line.

Ruby The complete bank program

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 gets), it gets the next line from this box.

Read the output against the input and each line tells a story. The failed withdraw grace 400 is refused and grace keeps her money. withdraw ada abc fails inside Integer("abc"), which raises ArgumentError; our helper amount_from translates that into the bank's own InvalidAmount, so the command loop needs only one rescue Bank::Error. This translation at the boundary is a common pattern: low-level errors are converted once, where they enter your domain.

The transfer to a missing account fails before any money moves, because transfer looks up both accounts first. The last line, balance ada after quit, is never read: break leaves the loop. The else branch of case/in handles anything that does not match, which is how fly away becomes a friendly message rather than a NoMatchingPatternError. Without an else, an unmatched case/in raises exactly that error.

Ideas to extend it

  • Add Account#history that prints the audit log as a table, or a statement command.
  • Make a SavingsAccount < Account with a monthly add_interest method and a withdrawal limit, and decide which parts of the audit log it shares with the base class.
  • Write Minitest tests for each rule: assert_raises(Bank::InsufficientFunds) { ... }.
  • Replace integer dollars with BigDecimal, or integer cents with a small Money value object built with Data.define.
  • Make transfer safe for threads with a Mutex, locking the two accounts in a fixed order (see Mutex, Queue and ConditionVariable).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do the custom exceptions inherit from a shared Bank::Error class?

    A common parent gives callers a choice between catching one specific problem or the whole family. Put the specific rescue clauses before the general one.
  2. 2. In withdraw, why is the balance changed only after the checks?

    Ruby does not undo assignments when an exception is raised. Validating first and changing state last keeps an operation all-or-nothing.
  3. 3. What does include Comparable give Account once <=> is defined?

    Comparable builds the comparison operators on top of <=>, and sort, min and max rely on the same method.
  4. 4. What happens in the case/in command loop when a line matches no pattern and there is no else?

    Unlike case/when, a case/in without an else raises NoMatchingPatternError for an unmatched value. The project adds an else for friendly messages.
  5. 5. Why does amount_from convert ArgumentError into Bank::InvalidAmount?

    Translating low-level errors where they enter the domain keeps the rest of the program free of knowledge about Integer()'s failure mode.

Summary

  • Start naive, run it, and let the failures tell you which rules the code needs.
  • Custom exceptions under a shared parent express domain rules; extra attributes such as needed and available give callers data instead of text to parse.
  • Validate first, change state last, so a failed operation changes nothing.
  • Comparable plus a single <=> gives ordering, min, max and sort for free.
  • A mixin module such as Audited adds behavior (a log) to any class without inheritance, and a private record method keeps the trail tamper-proof.
  • case/in makes a compact command dispatcher; translate low-level errors into domain errors at the boundary.

Next: Project: Inventory and Reports