Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 134 ยท Projects

Project: Bank Account Simulation

Build a small bank in Kotlin - a Money value class, accounts that protect their rules, sealed results instead of exceptions for business errors, atomic transfers and an audit log you can verify.

A bank is a good project for learning to protect rules. Money must not appear or vanish, balances must not go negative, and every change must be traceable. If a program can break such rules by accident, it will. In this project you design the code so that the rules are hard to break, and so that every failure is reported in a way the caller cannot ignore.

You will combine value classes, encapsulation, sealed classes, exceptions and custom exceptions, data classes and require/check. It is the third project; the previous one was the to-do manager and the next one is the inventory report.

Two kinds of failure

Before writing code, decide what can go wrong. There are two very different families:

  • Programmer errors. Depositing a negative amount, or asking for a transfer with an account that does not exist in the code at all. These are bugs. The right reaction is an exception (IllegalArgumentException, IllegalStateException), because the program should not carry on as if nothing happened.
  • Business outcomes. "Not enough funds" or "unknown account number typed by the customer" are normal, expected results. A customer can try to withdraw too much every day. These are better modeled as values, with a sealed type, so that the compiler forces callers to deal with each case.

We will use both, deliberately. The rule of thumb: if a correct program can still meet the situation, return a result; if it signals a bug, throw.

Step 1: money without floating point

Never store money in a Double. 0.1 + 0.2 is not exactly 0.3 in binary floating point, and such errors add up. The usual fix is to store the smallest unit as an integer: cents in a Long. A value class gives us a distinct type at almost no cost, so you cannot confuse "500 cents" with "500 accounts".

Kotlin Step 1 - a Money value class

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

The last two lines make the point: 0.1 + 0.2 prints 0.30000000000000004, while Money(10) + Money(20) is exactly Money(30). Because Money is a value class, == compares the cents. At run time it is just a Long most of the time, so there is no extra object per amount.

A value class gives type safety. The next TryIt fails on purpose, because a bare number is not a Money.

Kotlin A number is not Money (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 readln()), it gets the next line from this box.

The compiler reports an argument type mismatch: the actual type is Int, but Money was expected. This protects you from passing dollars where cents are expected, or a user id where an amount is expected. The fix is deposit(Money(500)).

Step 2: an account that guards its balance

An account must be the only place where its balance changes. We make the setter private so no outside code can write account.balance = .... Operations check their rules and return a sealed result.

Kotlin Step 2 - accounts and sealed results

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

An insufficient balance is a result: the customer simply cannot do it. A negative deposit is a bug: no correct caller builds one, so require throws. In the output you see both paths. The private set is what makes the account trustworthy: all changes to balance are in two functions that you can read and review.

Why not throw an InsufficientFundsException? You can, and many Java-style codebases do. The advantage of the sealed result is that Kotlin has no checked exceptions, so nothing forces a caller to handle a thrown exception, but an exhaustive when over a sealed result does force it. See custom exceptions and error design for the trade-off.

Step 3: a bank, transfers and an audit log

A transfer touches two accounts and must be atomic: either both change or neither. With our design that is easy to get right if we check everything first and only then change anything. The bank also writes an audit log of immutable entries. Real banks never edit history: they append.

Instead of a timestamp (which would make the output vary from run to run) every entry gets a sequence number.

Kotlin Step 3 - the bank with an audit 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 readln()), it gets the next line from this box.

Check how the design supports the rules:

  • transfer validates everything before it changes anything. After the checks, debit and credit cannot fail in a correct program. That is what makes the transfer atomic without any special machinery.
  • debit still uses check. It is internal, so only code in the same module can call it, and its precondition is a safety net. If a bug in transfer ever skipped the balance check, the program would stop instead of silently producing a negative balance.
  • The total money is the same before and after (150.00): transfers move money; they never create or destroy it. That is an invariant, and the next step turns it into a test.
  • The log is exposed as a copy. Nobody outside can delete or edit an entry.
  • Rejected attempts are logged too. In a real bank, failed attempts are often the most interesting part of the log.

Where would an exception be right?

open throws IllegalArgumentException when the number already exists. Whoever opens accounts (a program, not a customer typing) should know the numbers are unique. If you disagree, return a sealed result there too. The point is to choose consciously.

Step 4: a scripted day at the bank, with a checked invariant

Finally we drive the bank from text commands and verify the invariant after every step. The commands are read from stdin, one per line, in the form transfer FROM TO CENTS. This is a tiny version of what property-based tests do: run many operations and assert that something stays true.

Kotlin Step 4 - the simulation and the invariant

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

Every outcome prints a one-line summary. The check(...) after each transfer is the invariant. If you break transfer, for example by crediting the target before verifying the source balance, or by crediting twice, the check stops the program and names the line. Try it: change target.credit(amount) to target.credit(amount + amount) and run again.

Taking it further

  • Money overflow. Long cents can hold about 92 quadrillion dollars, but plus can still overflow. Use Math.addExact inside Money.plus so that overflow throws instead of wrapping around silently (see numbers).
  • Thread safety. If two threads call transfer at once, the balance check and the debit can interleave. You would need a lock or a single owner coroutine (shared mutable state).
  • Interest and fees. Add data class Fee(...) entries and test with fixed rounding rules; use BigDecimal with an explicit RoundingMode for percentages.
  • Event sourcing. Instead of storing balances, store only the log and derive the balances with fold. The audit log you built is already half of it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is money stored as Long cents in a value class instead of a Double?

    Floating point cannot represent values such as 0.1 exactly. Integer cents are exact, and the wrapper type adds safety without an extra object in most cases.
  2. 2. Which situation should be modeled as a sealed result rather than an exception?

    Insufficient funds is a normal business outcome a correct program meets every day. The other three are bugs.
  3. 3. What makes the transfer atomic in this design?

    Because validation comes first, debit and credit cannot fail afterwards, so both accounts change or neither does.
  4. 4. What does var balance: Money = Money(0); private set achieve?

    A private setter lets outsiders read the value while keeping every write inside the class, where rules can be enforced.

Summary

  • Store money in integer cents; wrap them in a value class for type safety.
  • Separate bugs (throw with require/check) from business outcomes (return sealed results).
  • Make state changes private to the class that owns the rules (private set, internal helpers).
  • Validate first, mutate afterwards, and operations that touch several objects become atomic.
  • Keep an append-only audit log, and expose it as a copy.
  • State invariants, such as "the total never changes", and check them in tests or simulations.

Next: Project: Inventory and Reports