Sub topic 14
How accounting software models debits and credits
This chapter assumes you know normal balances, the debit and credit rules, journal entries, posting, and the trial balance. It shows how the same ideas are stored in a database and checked in code.
Entries and lines, not two columns
Most systems do not store one row with a "debit account" and a "credit account". They store a journal entry header and several journal lines. A line holds an account, an amount, and a side. This handles entries with three or more accounts, such as a sale with tax, without a special case.
The account's type decides its normal balance. Software usually stores the type and derives the normal side, as the rules in earlier chapters do. It does not store a separate "increase side" per account.
Two common ways to store an amount
| Model | Stored as | Balance check |
|---|---|---|
| Side column | A positive amount plus `debit` or `credit` | Sum of debits equals sum of credits |
| Signed amount | One number, debit positive and credit negative | Sum of all lines equals zero |
The signed model makes the balance check a single sum. The side column model is easier to read in reports. Either way, the stored amount is never negative to mean "a debit of a negative amount". A negative number in the side column model is usually a bug.
A small ledger in Python
This example uses the signed model and the three transactions from the earlier chapters. It refuses to save an unbalanced entry, which is the check a real system runs before committing.
from collections import defaultdict
from decimal import Decimal
class Ledger:
def __init__(self):
self.lines = [] # (entry_id, account, signed_amount)
def post(self, entry_id, lines):
"""lines: list of (account, side, amount); amounts are positive."""
signed = []
for account, side, amount in lines:
if amount <= 0:
raise ValueError("amount must be positive")
if side not in ("debit", "credit"):
raise ValueError("side must be 'debit' or 'credit'")
signed.append((entry_id, account, amount if side == "debit" else -amount))
if sum(a for _, _, a in signed) != 0:
raise ValueError("entry is not balanced")
self.lines.extend(signed) # all lines are saved together or not at all
def balances(self):
totals = defaultdict(Decimal)
for _, account, amount in self.lines:
totals[account] += amount
return dict(totals)
ledger = Ledger()
ledger.post(1, [("Cash", "debit", Decimal("1000")), ("Owner Capital", "credit", Decimal("1000"))])
ledger.post(2, [("Cash", "debit", Decimal("500")), ("Service Revenue", "credit", Decimal("500"))])
ledger.post(3, [("Rent Expense", "debit", Decimal("300")), ("Cash", "credit", Decimal("300"))])
balances = ledger.balances()
print(balances["Cash"]) # 1200
print(sum(b for b in balances.values() if b > 0)) # 1500
print(-sum(b for b in balances.values() if b < 0)) # 1500The trial balance is not a stored table here. It is a query over all lines. In a database it is a GROUP BY account over the lines table. Because every saved entry sums to zero, the whole ledger always sums to zero.
Design choices that matter
- Use exact decimals. Store money as
Decimalin code andNUMERICin a database, or as integer cents. Binary floating point can make0.1 + 0.2differ from0.3, which breaks the zero-sum check. - Do not edit posted lines. To fix an error, post a reversing entry and then a correct one. This keeps an audit trail.
- Show friendly labels in the interface. Some products show "Money in" and "Money out" and store debits and credits underneath. Check which side the label maps to for each account type.
- Handle several currencies deliberately. Each line usually needs its own currency and a base-currency amount, and the zero-sum check applies to the base amounts.
Exercise
Exercise
In a signed-amount ledger (debit positive, credit negative), a customer pays a $200 invoice in cash. Write the two signed lines, and say what the sum of the lines must be.
Show answer
Cash is +200 (a debit, since cash is an asset that increases) and Accounts Receivable is -200 (a credit, since the asset decreases). The sum is 0, which is what the system checks before saving the entry.
Exercise
Why should a system store money as Decimal or integer cents instead of floats, given that it checks that each entry sums to zero?
Show answer
Floats cannot represent many decimal amounts exactly, so lines that should cancel can leave a tiny nonzero remainder. The balance check would then reject valid entries or accept wrong ones. Decimal or integer cents give exact sums.