Design Patterns Applied
Our Splitwise design uses 3 design patterns: Strategy is the core of the code; Command wraps expense creation for multi-level undo (its code below runs on our ExpenseService); Observer is the extension notifications would plug into — notifications are out of scope (see the Requirements), so our code has no observers yet. Let's examine WHY each fits, how it improves the design, and what the code would look like without it.
Strategy Pattern — Interchangeable Split Algorithms
Category: Behavioral (Fundamentals S12)
Problem it solves in our design:
Splitwise supports multiple ways to split an expense: equal, exact amounts, and percentage. Without Strategy, the ExpenseService.addExpense() method would need conditional logic for each split type:
# WITHOUT Strategy — violates Open/Closed Principle
def add_expense(self, split_type, amount, participants, shares):
if split_type == "EQUAL":
per_person = amount / len(participants)
splits = [Split(p, per_person) for p in participants]
elif split_type == "EXACT":
splits = [Split(p, s) for p, s in zip(participants, shares)]
elif split_type == "PERCENTAGE":
splits = [Split(p, amount * s / 100) for p, s in zip(participants, shares)]
# Adding a new type means modifying THIS methodEvery new split type (by shares, by weight, by income ratio) forces a change to addExpense() — violating the Open/Closed Principle (Fundamentals S6). Testing individual strategies in isolation is also impossible since they're embedded in control flow.
How we applied it:
SplitStrategyis the abstract interface with a single method:split(amount, participants, shares) → List[Split]EqualSplitStrategy,ExactSplitStrategy,PercentageSplitStrategyare concrete implementationsExpenseServicereceives the strategy as a parameter and callsstrategy.split()polymorphically — it never knows which algorithm runs- The client (UI/API layer) creates the appropriate strategy based on the user's choice and passes it in
Why Strategy and not alternatives?
- Template Method was considered, but split algorithms don't share a common skeleton — they're fundamentally different calculations. Strategy is better when algorithms are fully independent.
- Simple inheritance (subclassing Expense into EqualExpense, ExactExpense, etc.) was rejected because the split type is a behavior variation, not an identity variation. An expense's identity doesn't change based on how it's split.
- Enum + switch is the naive approach shown above — it works but violates OCP and makes unit testing harder.
Cross-reference: The Elevator System (DP8) uses the same pattern for scheduling algorithms (FCFS, SCAN, LOOK), and the Ride-Sharing Service (DP22) uses it for driver matching and pricing.
Observer Pattern — Balance Change Notifications
Category: Behavioral (Fundamentals S12)
Problem it solves in our design:
When an expense is added, multiple users' balances change. In a real Splitwise app, each affected user needs to be notified — via push notification, email, or in-app alert. Without Observer, the ExpenseService would need to explicitly know about every notification channel:
# WITHOUT Observer — ExpenseService coupled to notification logic
def add_expense(self, ...):
# ... create expense and update balances ...
send_push_notification(participant, "You owe $40")
send_email(participant, "New expense added")
update_in_app_badge(participant)
# Adding SMS requires modifying ExpenseService!This tightly couples business logic (expense management) with infrastructure concerns (notifications), violating the Single Responsibility Principle.
How it would plug in (an extension — our code sends no notifications):
The Observer pattern decouples expense creation from notification delivery:
BalanceObserveris the observer interface with a methodon_balance_changed(user, other_user, new_balance)- Concrete observers implement specific channels:
PushNotificationObserver,EmailObserver,InAppObserver ExpenseService(orBalanceSheet) acts as the subject, notifying registered observers after each balance update- New notification channels (SMS, Slack webhook) are added by implementing
BalanceObserver— zero changes toExpenseService
# WITH Observer — ExpenseService stays focused on business logic
class BalanceObserver(ABC):
@abstractmethod
def on_balance_changed(self, user: User, other_user: User,
new_balance: float) -> None:
pass
class PushNotificationObserver(BalanceObserver):
def on_balance_changed(self, user, other_user, new_balance):
# Send push notification to user
passWhy Observer and not alternatives?
- Direct method calls (as shown in the "before" code) create tight coupling and require modifying business logic for each new channel.
- Event bus / pub-sub is a more decoupled version of Observer suitable for distributed systems, but at the LLD level (in-process), the classic Observer is simpler and sufficient.
- Callback functions could work but don't provide the structured registration/deregistration that Observer offers.
Cross-reference: The Logging Framework (DP5) uses Observer for routing log messages to multiple sinks, and the Task Management System (DP7) uses it for task assignment notifications.
Command Pattern — Expense Undo
Category: Behavioral (Fundamentals S12)
Problem it solves in our design:
Users sometimes add expenses by mistake and need to undo them. Undoing an expense is not simply deleting a record — it requires reversing all balance changes that the expense caused. Our undo_expense() can do that on its own, because the expense keeps its splits: it reverses exactly those amounts, and since balances only add up, that is right whatever happened after (the Testing lesson's edge case 9 shows it with a settle-up in between). What it can't do is remember which expenses to undo, in which order, or redo one — without Command, the caller has to keep that history itself:
# WITHOUT Command — undo works, but the caller owns the history
e1 = service.add_expense(trip, alice, 120.00, "Dinner",
[alice, bob, charlie], EqualSplitStrategy())
e2 = service.add_expense(trip, bob, 90.00, "Gas",
[alice, bob, charlie], ExactSplitStrategy(),
[20.00, 40.00, 30.00])
# "Undo the last thing I did": the caller must have kept e2 and
# its group — nothing records the order of operations, and once
# undone, e2 is gone: there is no redo.
service.undo_expense(e2, trip)The real gap is history: with several expenses and settle-ups, the caller has to track which expense to undo next — and there is no redo.
How we applied it:
The Command pattern encapsulates each expense creation as a reversible operation:
AddExpenseCommandwraps theaddExpensecall and keeps the expense it createdexecute()creates the expense (calling it again afterundo()is a redo)undo()reverses exactly whatexecute()did, throughundo_expense()and the expense's own splits- A command history stack enables multi-level undo
# WITH Command — each expense is a reversible command
class AddExpenseCommand:
def __init__(self, service, group, payer, amount, description,
participants, strategy, shares=None):
self._service = service
self._params = (group, payer, amount, description,
participants, strategy, shares)
self._expense = None
def execute(self) -> Expense:
self._expense = self._service.add_expense(*self._params)
return self._expense
def undo(self) -> None:
if self._expense:
self._service.undo_expense(self._expense,
self._params[0])
self._expense = NoneWhy Command and not alternatives?
- Memento Pattern (snapshot entire system state before each expense) would work but is expensive — storing full balance snapshots for every expense in a system with millions of expenses is impractical.
- Event Sourcing (store all events and replay) is the distributed-systems version of Command. At the LLD level, Command is simpler and achieves the same goal.
- Simple delete (just remove the expense record) doesn't reverse balance changes — it leaves the system in an inconsistent state.
Cross-reference: The Task Management System (DP7) uses Command for undo/redo of task operations, and Chess (DP21) uses it for move history with take-back capability.
How the Patterns Work Together
The three patterns in Splitwise serve orthogonal concerns that combine cleanly:
- Strategy decides how to split — it calculates the individual shares
- Command wraps what happened — it makes the operation reversible
- Observer reacts to side effects — it notifies affected users
When a user adds an expense:
- The Command captures the intent and delegates to
ExpenseService - The Strategy computes splits without the service knowing the algorithm
- After balances are updated, Observers (once added) fire notifications to affected users
- If the user clicks "undo," the Command reverses everything — and Observers fire again with updated balances
This separation means you can change the notification system without touching split logic, add new split algorithms without touching undo logic, and modify undo behavior without affecting notifications. Each pattern owns exactly one axis of variation.