Skip to main content

Summary & Key Takeaways

Editorial

Design Recap

We designed a complete expense-sharing system modeled after Splitwise, tackling the challenge of splitting costs among groups of users with different algorithms and settling debts in at most N-1 transfers.

Core design decisions and their rationale:

  1. Strategy Pattern for split types — Equal, exact, and percentage splits are encapsulated as interchangeable algorithms behind the SplitStrategy interface. This was the pivotal decision: it ensures that the core ExpenseService never needs to change when new split types are added, directly honoring the Open/Closed Principle.

  2. Composition for Expense → Split — Each expense owns its splits because a split has no meaning outside its parent expense. Deleting or undoing an expense destroys its splits. This lifecycle binding is the textbook case for composition over association.

  3. Separate BalanceSheet class — Rather than tracking balances as a raw map on User, we encapsulated financial state in BalanceSheet. This follows SRP: User handles identity, BalanceSheet handles money. It also makes it straightforward to add balance history, currency-specific tracking, or snapshot capabilities later.

  4. Greedy debt simplification — The net-balance approach reduces potentially O(N²) pairwise debts to at most N-1 transfers — not always the fewest (+4, +3, +2 against -5, -4 takes greedy 4 transfers; 3 suffice). We chose greedy over the theoretically optimal (NP-hard) subset-sum minimization because it's fast, always settles everyone and stays within N-1.

  5. Undo from the expense's own record — An expense keeps its splits, so undo_expense() reverses exactly the balance changes it made, whatever came after; it checks first, so a second undo is refused. Wrapping creation in a Command (Design Patterns Applied) adds the history for multi-level undo and redo — the same pattern the Chess game (DP21) uses for move history.

Patterns Applied

PatternWhere AppliedOne-Line Rationale
Strategy (Fundamentals S12)SplitStrategy → EqualSplitStrategy, ExactSplitStrategy, PercentageSplitStrategyEncapsulate split algorithms so new types are added without modifying ExpenseService
Observer (Fundamentals S12) — extensionBalanceObserver → PushNotificationObserver, EmailObserver (not in our code: notifications are out of scope)Decouple balance changes from notification delivery channels
Command (Fundamentals S12)AddExpenseCommand with execute() / undo(), wrapping ExpenseService (Design Patterns Applied)Make expense creation reversible without reconstructing side effects

What Makes This a Good Design

  • Extensible: Adding a new split type (e.g., split by shares where one person pays 2x) requires only implementing SplitStrategy. Zero changes to Expense, ExpenseService, or BalanceSheet. With the Observer extension in place, a new notification channel would need only a new BalanceObserver.

  • Testable: Every component is testable in isolation. EqualSplitStrategy can be tested with various amounts and participant counts without creating users or groups. DebtSimplifier can be tested with mock users without real expenses. BalanceSheet can be tested without any other class.

  • SOLID compliant:

    • S (Single Responsibility): User handles identity, BalanceSheet handles money, ExpenseService handles orchestration, each strategy handles one algorithm.
    • O (Open/Closed): New split types can be added without modifying existing classes — and, with the Observer extension, notification channels. A different debt simplification algorithm would first need an interface for DebtSimplifier (another Strategy application).
    • L (Liskov Substitution): Any SplitStrategy implementation can be substituted wherever the interface is expected.
    • I (Interface Segregation): SplitStrategy asks each strategy for exactly one method, split() — its static to_cents() is shared, not implemented — so clients aren't forced to implement unused operations.
    • D (Dependency Inversion): ExpenseService depends on the SplitStrategy abstraction, not on concrete EqualSplitStrategy.
  • Financially correct: Rounding errors are explicitly handled. The conservation invariant (all balances sum to zero) is maintained across all operations. Bidirectional balance recording ensures consistency.

Extensions to Explore

  1. Split by Shares — Add a BySharesSplitStrategy where each participant specifies a weight (e.g., 2x for one person). This is a one-class addition that plugs directly into the existing Strategy infrastructure.

  2. Multi-Currency Support — Add a Currency enum and CurrencyConverter service. Balance sheets track per-currency balances. Debt simplification runs per-currency. This extends the model without breaking existing single-currency logic.

  3. Thread-Safe Balances — Make each whole operation atomic: one lock around add_expense, settle_up and undo_expense (threading.Lock in Python, synchronized in Java), since one expense changes two balance sheets per split. A lock inside BalanceSheet.updateBalance() alone lets another thread see half an expense, and a ConcurrentHashMap alone still loses updates (Testing & Edge Cases, follow-up 2). Apply concurrency patterns from Fundamentals S14 to handle concurrent expense additions.

  4. Expense Categories and Analytics — Add a Category enum (Food, Travel, Utilities) to Expense and build aggregation queries. This is a domain extension that doesn't affect the core splitting or balance logic.

Key Takeaways

  1. Strategy Pattern is the backbone of systems with multiple algorithms for the same task. Whenever you see "the system supports multiple ways to do X" in requirements, Strategy should be your first instinct. Splitwise has split strategies; the Elevator System (DP8) has scheduling strategies; the Ride-Sharing Service (DP22) has matching strategies.

  2. Financial systems demand explicit rounding control. Never rely on floating-point division to "just work." Always handle remainders explicitly (assign to the last participant, round toward zero, etc.) and validate that all amounts sum to the expected total after every operation.

  3. Debt simplification is a graph problem disguised as a finance problem. The pairwise debt network is a weighted directed graph. Simplification collapses it to net balances and greedily matches debtors with creditors. This pattern — transforming a messy graph into net flows — appears in financial clearing systems well beyond Splitwise.

  4. Undo is simple when an operation keeps a record of its effects. Adding an expense updates multiple balance sheets bidirectionally, but the expense keeps its splits, so undo reverses exactly them — nothing to reverse-engineer. Command goes one step further: it captures the operation as a first-class object, so a history of commands gives multi-level undo and redo. This is the same principle behind undo in text editors, move history in Chess (DP21), and transaction rollback in the Digital Wallet (DP16).

  5. Composition vs. Association is driven by lifecycle dependency, not just "has-a." Splits die with their expense (composition). Users outlive their groups (association). This distinction drives garbage collection, undo semantics, and cascade deletes — getting it wrong creates subtle bugs in any system with complex ownership.