Testing & Edge Cases
Testing Strategy
Testing an expense-sharing system demands more rigor than most LLD problems because financial correctness is non-negotiable. A rounding error that loses a penny per expense becomes millions of dollars of discrepancy at Splitwise's scale. Our testing strategy covers three levels:
Unit Tests — Individual Components:
EqualSplitStrategy: Verify splits sum to the exact expense amount, even with indivisible amountsExactSplitStrategy: Verify validation rejects amounts that don't sum to the totalPercentageSplitStrategy: Verify percentages must sum to 100%, and rounding remainder goes to the last participantBalanceSheet: Verify bidirectional balance updates, zero-balance cleanup, and net balance calculationDebtSimplifier: Verify output transactions settle all balances to zero in at most N-1 transactions
Integration Tests — Workflow Correctness:
- Full expense lifecycle: add expense → verify balances → settle up → verify balances return to zero
- Multi-expense scenario: add 5 expenses with different strategies → verify all balances are mutually consistent
- Undo workflow: add expense → verify balances → undo → verify balances return to pre-expense state
Invariant Tests — System-Wide Properties:
- Conservation of money: After every operation (add, settle, undo), the sum of all users' net balances must equal zero
- Bidirectional consistency: If Alice's balance sheet says Bob owes her $40, then Bob's balance sheet must say he owes Alice $40
- Reversible undo: Undoing an expense and then re-adding it must produce identical balances to the original state — and undoing the same expense twice is refused, so its balances can never be reversed twice
Edge Cases
These are the edge cases that distinguish a robust implementation from a naive one. An interviewer will probe these after you present the happy path.
1. Indivisible Equal Splits
$100 split equally among 3 people: $33.33 + $33.33 + $33.34 = $100. The last participant absorbs the $0.01 remainder. Without this handling, you lose a penny: $33.33 × 3 = $99.99. Our EqualSplitStrategy works in whole cents: 10,000 cents among 3 is 3,333 each with 1 cent left over, and that cent goes to the last participant.
2. Payer Not a Participant
Alice pays $60 for Bob and Charlie (Alice doesn't partake). The payer is NOT in the participants list. Bob and Charlie each owe Alice $30 — the full amount, not a split that includes Alice. Our code handles this naturally: the balance update loop processes all splits, and since Alice has no split entry, she's purely a creditor.
3. Payer Is the Only Participant
Alice pays $50 and she's the only participant (self-expense). No balance changes occur because the payer-participant check skips same-user splits. This is valid — it's a personal expense tracked for record-keeping.
4. Percentage Splits with Rounding Drift
$0.03 split 50% / 50%: each exact share is $0.015. Rounding both to the nearest cent gives $0.02 + $0.02 = $0.04 (a cent created), or $0.01 + $0.01 = $0.02 (a cent lost). Our PercentageSplitStrategy rounds each share down to the cent and computes the last participant's share as total - sum_of_others: $0.01 + $0.02 = $0.03, exact.
5. Exact Split Amounts Don't Sum Correctly
User passes exact amounts [$30, $40, $20] for a $100 expense. Sum = $90 ≠ $100. Our ExactSplitStrategy validates this upfront and raises ValueError. The expense is never created, and no balances are modified.
6. Settling More Than Owed
Bob owes Alice $40 and tries to settle $60. Our system allows this — it simply means Alice now owes Bob $20. The settle_up method adjusts balances mechanically. In a production system, you might add a warning or prevent overpayment, but the balance math handles it correctly.
7. Debt Simplification with Cycles
A owes B $10, B owes C $10, C owes A $10. Net balances: all zero. The simplifier correctly produces zero transactions — no money needs to change hands because the debts form a perfect cancellation cycle.
8. Large Group with Single Debtor
One person pays for everything. After 20 expenses, the payer has a large negative net balance (everyone owes them — negative means owed) and everyone else a positive one. The simplifier handles this correctly — N-1 transactions, each from a different participant to the single creditor.
9. Undo After Partial Settlement
Alice adds a $100 expense split with Bob. Bob owes $50. Bob settles $30. Now Bob owes $20. If Alice undoes the original expense, the $50 balance reversal makes Bob's balance = $20 - $50 = -$30 (Alice now owes Bob $30). This is mathematically correct — the settlement was independent of the expense. The system handles it, but a production app might warn the user.
Interview Follow-Up Questions
Questions an interviewer might ask after you present this design:
1. "How would you handle multi-currency expenses?"
Add a Currency enum and a CurrencyConverter service. Each expense stores its currency. Balance sheets track per-currency balances. Debt simplification runs per-currency or converts everything to a base currency at settlement time. The Strategy Pattern extends naturally — you could add a CurrencyAwareSplitStrategy decorator.
2. "What if two users add expenses to the same group simultaneously?"
In our in-memory design, balance updates are not thread-safe: updateBalance() reads, adds and writes back, so two threads can lose an update (in one of our runs, four threads × 50,000 updates kept about 58,000 in Java and 68,000 in Python). A lock inside updateBalance() alone is not enough either — one expense changes two balance sheets per split, so another thread can see half an expense: the balances not summing to zero (in our runs, a third of the reads in Python and two thirds in Java, while expenses were being added). Make each whole operation atomic: one lock around add_expense, settle_up and undo_expense (a synchronized method in Java, a threading.Lock in Python), or locks on the users involved, always taken in the same order (by user ID) so two operations can't deadlock. A ConcurrentHashMap (Java) does not fix it on its own — its getOrDefault then put still loses updates; merge() would make each update atomic, but not the operation. Processing every operation through a single-threaded command queue also works: it serializes them.
3. "Is the greedy debt simplification algorithm truly optimal?"
It guarantees at most N-1 transactions, but not always the fewest. With net balances of +4, +3 and +2 (owing) and -5 and -4 (owed), greedy makes 4 transfers, yet 3 suffice: the +4 settles the -4 on its own, and the +3 and +2 settle the -5. Spotting such cancelling subsets is the hard part — finding the true minimum is NP-hard (a subset-sum variant). Greedy is fast, always settles everyone and stays within N-1, which is good enough for us.
4. "How would you add recurring expenses?"
Create a RecurringExpense class that stores the expense template (amount, participants, strategy) and a Schedule (weekly, monthly). A RecurringExpenseScheduler extends this by periodically calling ExpenseService.addExpense() with the template parameters. This is a Scheduler pattern extension that doesn't modify existing code.
5. "How would this design change if you needed to support 10 million users?"
At that scale, the in-memory balance sheet becomes a database table with indexed lookups. Balance updates become transactional database operations (ACID). Debt simplification runs as a batch job per group, not in real-time. The class design stays the same — the domain model is persistence-agnostic. This is the boundary between LLD (what we designed) and System Design (how to deploy it).