Skip to content
Java 21·about 9 min read

Designing Object-Oriented Ledgers in Java 21

Why storing money as decimal floats causes quiet rounding bugs, and how whole pence numbers and clean class hierarchies keep balances exact.

Why this is hereCompanion notes for Java Banking Ledger documenting integer pence arithmetic and flexible fee rules.

Why Floating-Point Money Breaks Quickly

One of the first traps in introductory programming is storing money in a double. It looks fine for two or three test inputs until you run 0.1 + 0.2 and get 0.30000000000000004. In a ledger that processes hundreds of transfers and monthly interest runs, those tiny IEEE 754 binary rounding errors accumulate until account statements no longer balance.

When I built Java Banking Ledger (java-banking-ledger), I stored every balance, overdraft limit, and fee as a 64-bit integer count of pence (long). One hundred and fifty pounds is simply 15_000L (15000 pence). Addition, subtraction, and fee deductions become exact integer arithmetic with zero rounding drift.

java
// Storing balances in integer pence avoids floating-point rounding bugs
long openingBalancePence = 15_000L; // £150.00
long withdrawalPence     = 2_550L;  // £25.50
long remainingPence      = openingBalancePence - withdrawalPence; // 12_450p (£124.50)

Encapsulation and Abstract Base Classes

In university OOP modules, inheritance examples often use contrived Animal or Shape hierarchies that don't explain why you would actually use an abstract class in real software. A financial ledger is a much clearer fit: every account has an ID, an owner, a running balance in pence, and an append-only statement log, but different account types follow completely different rules when someone tries to withdraw money.

By making Account an abstract class with a private long balancePence field, no external caller—and not even a subclass—can arbitrarily overwrite the balance without recording a matching statement entry. Instead, subclasses only override canWithdraw(long totalDeductionPence):

java
public abstract class Account {
    private final String accountId;
    private long balancePence;
    private final FeePolicy feePolicy;

    protected abstract boolean canWithdraw(long totalDeductionPence);

    public void withdraw(String txId, long amountPence, String note) {
        long fee = feePolicy.calculateFeePence(amountPence);
        long total = amountPence + fee;
        if (!canWithdraw(total)) {
            throw new IllegalStateException("Insufficient funds on " + accountId);
        }
        this.balancePence -= total;
    }
}

A CheckingAccount allows the balance to dip below zero down to -overdraftLimitPence, while a SavingsAccount insists that (balancePence - totalDeductionPence) >= minimumReservePence. The core withdraw workflow stays in one place on Account, and polymorphism handles the policy check cleanly.

Swapping Fee Rules with a Strategy Interface

If fee logic is hardcoded inside Account subclasses, you quickly end up with awkward classes like ZeroFeeCheckingAccount vs FlatFeeCheckingAccount. Instead, extracting fee calculation into a single-method @FunctionalInterface lets you pass any fee rule into the constructor:

java
@FunctionalInterface
public interface FeePolicy {
    long calculateFeePence(long withdrawalAmountPence);

    static FeePolicy zeroFee() {
        return amount -> 0L;
    }

    static FeePolicy flatFee(long flatFeePence) {
        return amount -> flatFeePence;
    }
}

Because FeePolicy is a functional interface, tests can pass FeePolicy.flatFee(25L) or a custom lambda without needing extra boilerplate classes.

Immutable Audit Trails with Java 21 Records

Every time an account balance changes, the ledger appends a TransactionEntry to the account's history. Java 21 record types are ideal here because audit entries should never be mutated after they are created:

java
public record TransactionEntry(
    String transactionId,
    String accountId,
    EntryType type,
    long amountPence,
    long balanceAfterPence,
    String description,
    Instant timestamp
) {}

Combined with Collections.unmodifiableList(ledgerEntries) on getStatement(), callers can inspect every historical transaction and verify balanceAfterPence without any risk of tampering with the internal list.

More Guides & Notes