Skip to main content

Class Diagram

Editorial

Purpose of the Class Diagram

The class diagram is the structural blueprint of our Splitwise system. It answers:

  • What classes exist and what responsibilities does each carry?
  • What attributes and methods does each class expose?
  • How do classes relate — through composition, association, or inheritance?

We'll derive every class directly from our 10 functional requirements. No class exists without a requirement-driven justification, and no requirement is left unaddressed by the model.

Identifying Classes from Requirements

Using the noun/verb extraction technique from Fundamentals S8, we analyze our requirements:

Key Nouns → Candidate Classes:

RequirementNouns FoundCandidate Class
R1: User managementuser, user ID, name, email, phone number, balance sheetUser, BalanceSheet
R2: Group managementgroup, group membersGroup
R3: Add expenseexpense, payer, amount, participantsExpense
R4-R6: Split typesequal split, exact split, percentage splitSplitStrategy hierarchy
R4-R6: Individual sharesplit, share amountSplit
R7: Balance trackingpairwise balance, balance mapBalanceSheet (tracks per-user balances)
R8: Debt simplificationsimplified transactionsDebtSimplifier, Transaction
R9: Expense historyexpenses a user is involved in, group filternone: a query on the stored expenses, ExpenseService.getExpenseHistory()
R10: Settle uppayment, settlementnone: an operation that updates two balance sheets, ExpenseService.settleUp()

Key Verbs → Candidate Methods:

  • "add expense" → ExpenseService.addExpense()
  • "split equally/exactly/by percentage" → SplitStrategy.split()
  • "update balance" → BalanceSheet.updateBalance()
  • "simplify debts" → DebtSimplifier.simplify()
  • "settle up" → ExpenseService.settleUp()
  • "undo expense" → ExpenseService.undoExpense() (Design Patterns Applied wraps it in a command, AddExpenseCommand.undo())
  • "view expense history" → ExpenseService.getExpenseHistory()

Design decisions at this stage:

  • Split is a separate class (not just a number) because each participant's share needs to track who owes what to whom.
  • BalanceSheet is owned by User — each user has exactly one balance sheet that tracks all their per-user debts.
  • SplitStrategy is an interface — the Strategy Pattern lets us add new split types (by shares, by weight) without modifying Expense.

Defining Relationships

Now let's determine how these classes connect:

  • User ◆→ BalanceSheet — Composition: A balance sheet cannot exist without its owning user. Deleting a user destroys their balance sheet. Multiplicity: exactly 1.

  • Group -- User — Association: A group references its members, but users exist independently of any group. Multiplicity: 0..* — a new group starts empty, and addMember() adds each user once.

  • Expense -- User (payer) — Association: An expense references who paid, but the user exists independently. Multiplicity: exactly 1 payer per expense.

  • Expense ◆→ Split — Composition: Splits are created as part of an expense and have no meaning outside it. Each expense composes 1..* splits. Deleting an expense destroys its splits.

  • Split -- User (participant) — Association: Each split references the participant who owes their share. The user exists independently.

  • Expense -- SplitStrategy — Association: The expense records the split strategy that calculated its shares (the ExpenseService calls its split()). The strategy is stateless and can be shared across expenses.

  • SplitStrategy △ EqualSplitStrategy, ExactSplitStrategy, PercentageSplitStrategy — Inheritance/Implements: Concrete strategies implement the SplitStrategy interface. Each encapsulates one splitting algorithm.

  • ExpenseService ⇢ Group — Dependency: The service receives a group as a parameter when it adds or undoes an expense, and stores no reference to it — a dependency (dashed arrow), not an association.

  • ExpenseService → Expense — Association: The service keeps every expense it creates, with or without a group, in creation order — the list that answers expense history (R9). Multiplicity: 0..* expenses.

  • Group ◆→ Expense — Composition: A group owns the expenses added to it; undoing an expense removes it from its group. An expense created without a group (R2) belongs to none, so the group end is 0..1.

  • DebtSimplifier ⇢ User, Transaction — Dependency: simplify(users) nets each user's balances with the other users it is given and creates the Transaction value objects it returns; it stores neither.

Why Composition between Expense and Split?
A split is not a standalone entity — it represents one participant's share within a specific expense. If the expense is deleted (or undone), its splits must be destroyed too. The split's lifecycle is bound to the expense, which is the hallmark of composition.

Why Association (not Composition) between Group and User?
A user can belong to multiple groups and exists independently of any group. Deleting a group doesn't delete its members. This is association — both sides have independent lifecycles.

Build the Class Diagram

Let's construct the diagram step by step, starting with the core domain entities and layering in patterns: first users and groups, then expenses and their splits, then the split strategies, the service that ties them together, and finally the debt simplifier.

Build it below: each step places its classes, then asks how each pair is related — composition or aggregation, association, realization, dependency — and the multiplicity the lesson states, before it shows the reason. Explore opens any class into its full UML box. Objects live runs the code lesson's usage example a step at a time, in Python or in Java: three users, each with the balance sheet it composes, the trip and its members, the service's list, and three expenses split equally, by exact amounts and by percentages — then a settle-up and an undo.

Interactive: build the Splitwise class diagram in five steps — users and groups, expenses and splits, the split strategies, the service, debt simplification — predicting each relationship's kind and multiplicity, with the lesson's reasons; explore every class's members; and step through the code lesson's usage example in Python or Java: the calls each statement makes, what it prints, and the objects — every user's balance sheet, the group, the service, the expenses — with four predictions on the way.

Complete Class Diagram

The complete UML class diagram of the Splitwise system, with the course code's Java member names (getters not shown; addExpense's seven parameters elided). ExpenseService (expenses: List<Expense>; addExpense(…): Expense, settleUp(payer, payee, amount), undoExpense(expense, group), getExpenseHistory(user, group): List<Expense>) has a «use» dependency on Group and an association to Expense (expenses, 0..*). Group (groupId, name, members, expenses; addMember, addExpense, removeExpense) has an association to User (members, 0..*) and composes Expenses (0..1 group, 0..* expenses). User (userId, name, email, phone, balanceSheet; getBalance(otherUserId), getNetBalance()) composes one BalanceSheet (balances: Map<String, Double>; updateBalance(userId, amount), getBalance(userId), getNetBalance()). Expense (expenseId, payer, amount, description, splits, strategy, createdAt) has associations to User (payer, 1) and SplitStrategy (strategy, 1) and composes Splits (1..*); each Split (user, amount) has an association to User (user, 1). The interface SplitStrategy (split(amount, participants, shares): List<Split>, and the static toCents(amount): long, underlined) is realized by EqualSplitStrategy, ExactSplitStrategy and PercentageSplitStrategy. DebtSimplifier (simplify(users): List<Transaction>) has a «use» dependency on User and a «create» dependency on Transaction (fromUser, toUser, amount). A legend explains association, composition, realization and dependency.

Key Design Decisions

1. Why Strategy Pattern for Split Types (not if/else)?

Without Strategy, Expense would contain a switch/if-else block for each split type — and every new split type (by shares, by weight, by income ratio) would require modifying Expense. This directly violates the Open/Closed Principle (Fundamentals S6). With Strategy, each split algorithm is a separate class implementing SplitStrategy. Adding BySharesSplitStrategy later requires zero changes to existing code.

2. Why Composition between Expense and Split?

A Split represents one participant's share within a specific expense. It has no identity outside that expense — you'd never reference a split independently. If an expense is undone (deleted), its splits must be destroyed. This lifecycle dependency is the textbook definition of composition.

3. Why a Separate BalanceSheet Class (not just a Map on User)?

Encapsulating the balance map inside BalanceSheet follows the Single Responsibility Principle (Fundamentals S6). The User class handles identity; BalanceSheet handles financial state. This separation makes it easy to add features like balance history, currency-specific sheets, or balance snapshots without bloating User.

4. Why DebtSimplifier is a Separate Class?

Debt simplification is a complex graph algorithm that operates on multiple users' balances. Putting it inside Group or ExpenseService would overload those classes. As a standalone class, DebtSimplifier is independently testable and could be swapped for a different algorithm (e.g., min-cost flow vs. greedy) — potentially another Strategy application.

5. Why Transaction as a Value Object?

Transaction represents the output of debt simplification — "User A should pay User B $X." It's a data carrier with no behavior, no lifecycle of its own, and no identity beyond its fields. This makes it a classic value object.