Home

Debits, Credits, and Invariants

· 2 min read

Before I worked on accounting software, I thought of correctness as "the tests pass." Accounting changed that. In accounting, correctness is a rule that must hold every single time, for every customer, forever.

The oldest one is also the most beautiful: for every journal entry, total debits equal total credits. It has survived for five hundred years because it makes a whole class of mistakes impossible to hide.

Invariants beat checks

A check asks "is this one thing right?" An invariant says "this can never be wrong." The difference matters when your app writes the same kind of record from a dozen places: invoices, payments, credit notes, inventory adjustments, imports.

If each of those paths is responsible for balancing its own entry, one of them eventually won't. If the entry itself refuses to exist unbalanced, none of them can.

class JournalEntry < ApplicationRecord
  validate :debits_equal_credits

  private
    def debits_equal_credits
      return if lines.sum(&:debit) == lines.sum(&:credit)
      errors.add(:base, "debits and credits must balance")
    end
end

Better still, push the rule down to the database, where no code path can skip it.

Find the conservation laws

Every domain has rules like this, they're just less famous. Stock in equals stock out plus stock on hand. An invoice's total equals the sum of its lines plus tax. A refund can never exceed what was paid.

When I start on a new feature now, the first question I ask isn't "what are the screens?" It's "what must always be true?" Write those down, enforce them in one place, and most bugs become impossible instead of merely unlikely.

Accountants figured out data integrity centuries before we had databases.