Sub topic 14
How Accounting Software Models Debits and Credits
This chapter assumes you can write a balanced journal entry, know the normal balance of each of the five account types, and can read short Python programs. It shows how the manual rules from earlier chapters become data structures and checks in software, and where those systems commonly go wrong.
The Core Model: Accounts, Entries, and Lines
Nearly every accounting system stores three kinds of records:
- Account: a code, a name, and a type (asset, liability, equity, revenue, or expense). The type determines the normal balance.
- Journal entry (also called a transaction): a header with a date, a memo, and an identifier. It holds no money amounts itself.
- Entry line (also called a posting or split): one amount against one account, belonging to one journal entry.
A T-account does not exist as a stored object. The ledger is a query: all lines for an account, summed. "Posting" in software therefore usually means writing the lines, or marking an entry as final. The system does not copy numbers into a second book.
Three Ways to Store Debit and Credit
Systems differ in how a line records its side.
| Representation | A $500 debit looks like | A $500 credit looks like | Trade-off |
|---|---|---|---|
| Two columns | debit=500, credit=0 | debit=0, credit=500 | Matches paper journals and is easy for accountants to read. Allows invalid rows with both columns filled or both zero. |
| Amount plus side | amount=500, side="debit" | amount=500, side="credit" | Amount is always positive. Needs a check that the side is one of two values. |
| Signed amount | amount=+500 | amount=-500 | A balanced entry sums to zero. Needs a clear convention for the sign. |
The choice affects only storage and convenience. The accounting is the same in all three. Two-column designs usually add a database constraint so that exactly one column is nonzero. Signed designs make the balance rule a single sum.
The examples below use the signed form: positive means debit, negative means credit. This is a storage convention. It does not say that credits are negative in any moral or financial sense.
Money Must Not Be a Float
Binary floating point cannot represent most decimal fractions exactly. Adding 0.10 + 0.20 in Python gives 0.30000000000000004. A balance check that compares sums with == would then reject valid entries or, worse, hide small errors.
Two safe choices:
- Use a decimal type such as Python's
Decimal. Build values from strings, not floats:Decimal("0.10"). - Store integer minor units, for example cents, and convert only for display. Databases and payment APIs often do this.
Also decide the precision for each currency. Most currencies use two decimal places, but some use none or three. A system that supports several currencies stores the currency with each amount, and each entry normally balances within one currency.
Enforcing the Balance Invariant
The central rule is that the sum of the signed line amounts in an entry is exactly zero. A well-built system enforces it at the point of writing, and does not rely on a report to catch violations afterward. Typical checks:
- At least two lines.
- No line with a zero amount.
- Every line refers to an account that exists and is open for posting.
- Amounts fit the currency's precision.
- The total is zero.
The following program implements a small ledger with these checks. It stores entries as immutable objects, derives all balances from lines, and produces a trial balance.
from collections import defaultdict
from dataclasses import dataclass
from decimal import Decimal
DEBIT_NORMAL = {"asset", "expense"}
CENT = Decimal("0.01")
@dataclass(frozen=True)
class Line:
account: str
amount: Decimal # positive = debit, negative = credit
@dataclass(frozen=True)
class Entry:
id: int
memo: str
lines: tuple
def dr(account, amount):
return Line(account, Decimal(amount))
def cr(account, amount):
return Line(account, -Decimal(amount))
class Ledger:
def __init__(self, accounts):
self.accounts = dict(accounts) # name -> type
self.entries = []
def post(self, memo, lines):
lines = tuple(lines)
if len(lines) < 2:
raise ValueError("an entry needs at least two lines")
for line in lines:
if line.account not in self.accounts:
raise ValueError(f"unknown account: {line.account}")
if line.amount == 0:
raise ValueError("zero-amount line")
if line.amount != line.amount.quantize(CENT):
raise ValueError("amount has more than 2 decimal places")
if sum((l.amount for l in lines), Decimal("0")) != 0:
raise ValueError("entry is not balanced")
entry = Entry(len(self.entries) + 1, memo, lines)
self.entries.append(entry)
return entry
def reverse(self, entry_id):
original = self.entries[entry_id - 1]
flipped = [Line(l.account, -l.amount) for l in original.lines]
return self.post(f"Reversal of #{entry_id}: {original.memo}", flipped)
def net(self, account):
"""Signed net: debits minus credits."""
return sum(
(l.amount for e in self.entries for l in e.lines if l.account == account),
Decimal("0"),
)
def balance(self, account):
"""Balance in the account type's normal direction."""
net = self.net(account)
return net if self.accounts[account] in DEBIT_NORMAL else -net
def trial_balance(self):
debits = credits = Decimal("0")
for account in self.accounts:
net = self.net(account)
if net > 0:
debits += net
else:
credits += -net
return debits, credits
ledger = Ledger({
"Cash": "asset",
"Owner Capital": "equity",
"Service Revenue": "revenue",
"Rent Expense": "expense",
})
ledger.post("Owner invests", [dr("Cash", "1000"), cr("Owner Capital", "1000")])
ledger.post("Service income", [dr("Cash", "500"), cr("Service Revenue", "500")])
ledger.post("Pay rent", [dr("Rent Expense", "300"), cr("Cash", "300")])
print(ledger.balance("Cash")) # 1200
print(ledger.balance("Service Revenue")) # 500
print(ledger.trial_balance()) # (Decimal('1500'), Decimal('1500'))
try:
ledger.post("Typo", [dr("Cash", "100"), cr("Service Revenue", "90")])
except ValueError as error:
print(error) # entry is not balancedNotice that trial_balance can never fail in this design. Every entry sums to zero, so total debits always equal total credits. The trial balance is a consistency check that is guaranteed by construction. That is useful, but see the limits below.
Correcting Errors: Reversals, Not Edits
Accounting records are an audit trail. Editing or deleting a posted line destroys the evidence of what was previously reported. Software therefore treats posted entries as append-only:
- To cancel an entry, post a reversing entry with every line's side flipped.
- To fix a wrong amount or account, reverse the original and post a correct entry. Some systems link the three records together.
- To undo something that never took effect, many systems use a draft state. Drafts can be changed or deleted, and posting locks them.
ledger.reverse(3) # cancel the rent payment
print(ledger.balance("Rent Expense")) # 0
print(ledger.balance("Cash")) # 1500
print(ledger.trial_balance()) # (Decimal('1500'), Decimal('1500'))Period locks add a further control. After a month is closed, the system rejects new entries dated in it, so corrections go into the current open period.
Presenting Balances to Users
Storage sign and display sign are separate decisions. A signed ledger returns net debit minus credit. A user looking at a liability account expects to see "owed: 800", not "-800". Software converts using the account type, exactly as the balance method does.
| Account | Stored net (debit minus credit) | Normal side | Displayed balance |
|---|---|---|---|
| Cash | +1,200 | Debit | 1,200 |
| Loan Payable | -800 | Credit | 800 |
| Service Revenue | -500 | Credit | 500 |
| Rent Expense | +300 | Debit | 300 |
An account whose net sign is opposite to its normal side has an abnormal balance. Examples are a cash account that is overdrawn or a customer account holding a credit. Good software shows this as a negative number in the display direction, for example -50 on an asset, and does not silently flip it. Contra accounts such as Accumulated Depreciation are different. They are separate accounts with their own type or flag, so their credit-normal balance is expected and gets reported against the related asset.
Failure Modes and Design Gotchas
- Float arithmetic. Rounding drift breaks the zero-sum check. Use decimals or integers.
- Unbalanced writes across several requests. If an API creates the entry header and then adds lines one at a time, a crash can leave a partial entry. Write the header and all lines in one database transaction, and validate the sum before commit.
- Mixed currencies. Lines in different currencies cannot be summed to zero directly. Systems either require each entry to balance per currency or add explicit gain/loss lines using an exchange rate.
- Sign confusion in imports. A bank file may show withdrawals as positive. Mapping them without checking the account type flips debits and credits, though the entry still balances. This is a balanced-but-wrong error.
- Stale cached balances. Many systems store running balances for speed. If a cache is updated separately from the lines, the two can disagree. Treat the lines as the source of truth and rebuild the cache from them in tests.
- Misplaced trust in the trial balance. It does not detect a wrong account, a missing entry, an entry posted twice, or errors that offset each other.
Closing Periods in Software
Closing entries from earlier chapters are often automated. At period end, many systems either post explicit closing entries that zero revenue and expense accounts into retained earnings, or compute "current period earnings" on reports without posting anything. The second approach leaves the lines untouched and reports revenue minus expenses as an equity figure. Check which approach a system uses before assuming a revenue account starts the new year at zero.
Exercise
A developer stores each line with a positive amount and a side field set to "debit" or "credit". An import script reads a bank statement and records every withdrawal as a debit to Cash and a credit to Expenses, because the statement shows withdrawals as positive numbers. Every entry passes the balance check. What is wrong, and what check or design change would catch it?
Show answer
A withdrawal reduces Cash, which is a debit-normal asset, so it needs a credit to Cash and a debit to the expense. The script has the sides reversed. The entries balance because the balance rule only compares total debits with total credits and does not check which account is on which side. The error would not appear in the trial balance. A fix is to map statement direction to sides using the account type, and to add tests that compare the resulting Cash balance with the bank's closing balance (a reconciliation). A rule that flags expense accounts with a net credit balance would also surface the problem.
Exercise
Using the Ledger class above, what does ledger.trial_balance() return after posting only [dr("Cash", "250.00"), cr("Service Revenue", "250.00")] to a new ledger, and why can it never return unequal totals?
Show answer
It returns (Decimal('250.00'), Decimal('250.00')). The post method rejects any entry whose signed line amounts do not sum to zero, so each stored entry adds equal amounts to the debit side and the credit side. The totals are equal by construction.