Skip to main content

Code Implementation

Editorial

Implementation Overview

We'll implement the Splitwise system class by class, following our class diagram exactly. Each class maps directly to what we designed.

Implementation order:

  1. Split — the value object representing one participant's share
  2. SplitStrategy interface and concrete strategies (Equal, Exact, Percentage)
  3. BalanceSheet — tracks per-user debts
  4. User — the central actor
  5. Expense — the core domain entity
  6. Group — organizes users and expenses
  7. ExpenseService — orchestrates the workflow
  8. Usage Example — a realistic multi-expense scenario

Split — Participant Share

A Split is a value object that represents one participant's computed share of an expense. It holds a reference to the user and the dollar amount they owe. Splits are created by the split strategy and owned (composed) by the expense.

from dataclasses import dataclass
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from user import User


@dataclass
class Split:
    """One participant's share of an expense."""
    user: 'User'
    amount: float

    def __repr__(self) -> str:
        return f"Split(user={self.user.name}, amount={self.amount:.2f})"
public class Split {
    private final User user;
    private final double amount;

    public Split(User user, double amount) {
        this.user = user;
        this.amount = amount;
    }

    public User getUser() { return user; }
    public double getAmount() { return amount; }

    @Override
    public String toString() {
        return String.format("Split(user=%s, amount=%.2f)", user.getName(), amount);
    }
}

SplitStrategy — The Strategy Interface and Concrete Strategies

The SplitStrategy interface defines one method each strategy implements: split(). A static helper they share, to_cents() (Java: toCents()), turns an amount into whole cents and rejects anything finer. Each concrete strategy encapsulates one splitting algorithm. This is the Strategy Pattern (Fundamentals S12) — the ExpenseService calls split() polymorphically without knowing which algorithm runs.

Key implementation details:

  • EqualSplitStrategy: Divides evenly, in whole cents. If $100 is split among 3, each gets $33.33, and the last participant absorbs the $0.01 remainder to maintain financial correctness.
  • ExactSplitStrategy: Uses caller-specified amounts, one per participant. Validates that the sum of exact amounts equals the total.
  • PercentageSplitStrategy: Converts percentages to dollar amounts. Validates that percentages sum to 100. Assigns rounding remainder to the last participant.
  • All three split whole cents — each share rounded down to the cent, the remainder to the last participant — so the shares always add up to the total, and Python and Java split every amount the same way. Each rejects an expense with no participants; exact and percentage also reject a share list of the wrong length, and to_cents() an amount finer than a cent.
from abc import ABC, abstractmethod
from typing import List


class SplitStrategy(ABC):
    """Interface for split calculation algorithms."""

    @abstractmethod
    def split(self, amount: float, participants: List['User'],
              shares: List[float]) -> List[Split]:
        """Calculate splits for the given amount and participants."""
        pass

    @staticmethod
    def to_cents(amount: float) -> int:
        """An amount as a whole number of cents; anything finer is rejected,
        so no penny can be lost or created."""
        cents = round(amount * 100)
        if abs(amount * 100 - cents) > 1e-6:
            raise ValueError(f"{amount} is not a whole number of cents")
        return cents


class EqualSplitStrategy(SplitStrategy):
    """Split an expense equally among all participants."""

    def split(self, amount: float, participants: List['User'],
              shares: List[float]) -> List[Split]:
        if not participants:
            raise ValueError("An expense needs at least one participant")
        # In whole cents: each share rounded down to the cent...
        per_person, remainder = divmod(self.to_cents(amount), len(participants))
        splits = [Split(p, per_person / 100) for p in participants]
        # ...and the last participant also takes the remainder
        if remainder > 0:
            splits[-1] = Split(participants[-1], (per_person + remainder) / 100)
        return splits


class ExactSplitStrategy(SplitStrategy):
    """Split an expense by exact amounts per participant."""

    def split(self, amount: float, participants: List['User'],
              shares: List[float]) -> List[Split]:
        if not participants:
            raise ValueError("An expense needs at least one participant")
        if len(shares) != len(participants):
            raise ValueError(
                f"{len(shares)} amounts for {len(participants)} participants"
            )
        cents = [self.to_cents(s) for s in shares]
        if sum(cents) != self.to_cents(amount):
            raise ValueError(
                f"Exact amounts sum to {sum(cents) / 100:.2f}, "
                f"but expense is {amount:.2f}"
            )
        return [Split(p, c / 100) for p, c in zip(participants, cents)]


class PercentageSplitStrategy(SplitStrategy):
    """Split an expense by percentages per participant."""

    def split(self, amount: float, participants: List['User'],
              shares: List[float]) -> List[Split]:
        if len(shares) != len(participants):
            raise ValueError(
                f"{len(shares)} percentages for {len(participants)} participants"
            )
        # Percentages in hundredths of a percent (two decimals at most)
        basis = [self.to_cents(pct) for pct in shares]
        if sum(basis) != 10000:
            raise ValueError(
                f"Percentages sum to {sum(shares):.2f}%, not 100%"
            )
        cents = self.to_cents(amount)
        splits = []
        given = 0
        for i, (p, b) in enumerate(zip(participants, basis)):
            if i == len(participants) - 1:
                # Last participant gets the remainder
                share = cents - given
            else:
                share = cents * b // 10000  # rounded down to the cent
                given += share
            splits.append(Split(p, share / 100))
        return splits
import java.util.List;
import java.util.ArrayList;

public interface SplitStrategy {
    List<Split> split(double amount, List<User> participants,
                      List<Double> shares);

    /** An amount as a whole number of cents; anything finer is rejected,
     *  so no penny can be lost or created. */
    static long toCents(double amount) {
        long cents = Math.round(amount * 100);
        if (Math.abs(amount * 100 - cents) > 1e-6) {
            throw new IllegalArgumentException(
                amount + " is not a whole number of cents");
        }
        return cents;
    }
}

public class EqualSplitStrategy implements SplitStrategy {

    @Override
    public List<Split> split(double amount, List<User> participants,
                             List<Double> shares) {
        int n = participants.size();
        if (n == 0) {
            throw new IllegalArgumentException(
                "An expense needs at least one participant");
        }
        // In whole cents: each share rounded down to the cent...
        long cents = SplitStrategy.toCents(amount);
        long perPerson = cents / n, remainder = cents % n;
        List<Split> splits = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            splits.add(new Split(participants.get(i), perPerson / 100.0));
        }
        // ...and the last participant also takes the remainder
        if (remainder > 0) {
            int last = n - 1;
            splits.set(last, new Split(participants.get(last),
                                       (perPerson + remainder) / 100.0));
        }
        return splits;
    }
}

public class ExactSplitStrategy implements SplitStrategy {

    @Override
    public List<Split> split(double amount, List<User> participants,
                             List<Double> shares) {
        if (participants.isEmpty()) {
            throw new IllegalArgumentException(
                "An expense needs at least one participant");
        }
        if (shares.size() != participants.size()) {
            throw new IllegalArgumentException(String.format(
                "%d amounts for %d participants", shares.size(), participants.size()));
        }
        long[] cents = new long[shares.size()];
        long sum = 0;
        for (int i = 0; i < cents.length; i++) {
            cents[i] = SplitStrategy.toCents(shares.get(i));
            sum += cents[i];
        }
        if (sum != SplitStrategy.toCents(amount)) {
            throw new IllegalArgumentException(
                String.format("Exact amounts sum to %.2f, but expense is %.2f",
                              sum / 100.0, amount));
        }
        List<Split> splits = new ArrayList<>();
        for (int i = 0; i < participants.size(); i++) {
            splits.add(new Split(participants.get(i), cents[i] / 100.0));
        }
        return splits;
    }
}

public class PercentageSplitStrategy implements SplitStrategy {

    @Override
    public List<Split> split(double amount, List<User> participants,
                             List<Double> shares) {
        if (shares.size() != participants.size()) {
            throw new IllegalArgumentException(String.format(
                "%d percentages for %d participants", shares.size(), participants.size()));
        }
        // Percentages in hundredths of a percent (two decimals at most)
        long[] basis = new long[shares.size()];
        long basisSum = 0;
        for (int i = 0; i < basis.length; i++) {
            basis[i] = SplitStrategy.toCents(shares.get(i));
            basisSum += basis[i];
        }
        if (basisSum != 10000L) {
            double pctSum = shares.stream().mapToDouble(Double::doubleValue).sum();
            throw new IllegalArgumentException(
                String.format("Percentages sum to %.2f%%, not 100%%", pctSum));
        }
        long cents = SplitStrategy.toCents(amount);
        List<Split> splits = new ArrayList<>();
        long given = 0;
        for (int i = 0; i < participants.size(); i++) {
            long share;
            if (i == participants.size() - 1) {
                share = cents - given;  // Last participant gets the remainder
            } else {
                // rounded down to the cent
                share = cents * basis[i] / 10000;
                given += share;
            }
            splits.add(new Split(participants.get(i), share / 100.0));
        }
        return splits;
    }
}

BalanceSheet — Per-User Debt Tracking

Each User owns exactly one BalanceSheet (composition). The balance sheet is a map from other user IDs to the net amount owed. A positive value means "I owe them"; a negative value means "they owe me."

This bidirectional recording — where both parties track the same debt — ensures either user can query their balances independently. It's a deliberate consistency choice that simplifies the query path.

from collections import defaultdict


class BalanceSheet:
    """Tracks per-user pairwise balances.

    Positive balance = I owe them.
    Negative balance = they owe me.
    """

    def __init__(self) -> None:
        self._balances: dict[str, float] = defaultdict(float)

    def update_balance(self, user_id: str, amount: float) -> None:
        """Add amount to the balance with user_id."""
        self._balances[user_id] = round(
            self._balances[user_id] + amount, 2
        )
        # Clean up zero balances
        if self._balances[user_id] == 0:
            del self._balances[user_id]

    def get_balance(self, user_id: str) -> float:
        """Get balance with a specific user."""
        return self._balances.get(user_id, 0.0)

    def get_net_balance(self) -> float:
        """Total net balance: positive = net debtor, negative = net creditor."""
        return round(sum(self._balances.values()), 2)

    def get_all_balances(self) -> dict[str, float]:
        """Return a copy of all non-zero balances."""
        return dict(self._balances)
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;

public class BalanceSheet {
    private final Map<String, Double> balances = new HashMap<>();

    public void updateBalance(String userId, double amount) {
        double current = balances.getOrDefault(userId, 0.0);
        double updated = Math.round((current + amount) * 100.0) / 100.0;
        if (updated == 0.0) {
            balances.remove(userId);
        } else {
            balances.put(userId, updated);
        }
    }

    public double getBalance(String userId) {
        return balances.getOrDefault(userId, 0.0);
    }

    public double getNetBalance() {
        return Math.round(
            balances.values().stream()
                .mapToDouble(Double::doubleValue).sum() * 100.0
        ) / 100.0;
    }

    public Map<String, Double> getAllBalances() {
        return Collections.unmodifiableMap(balances);
    }
}

User — The Central Actor

The User class holds identity information and composes a BalanceSheet. Following the Single Responsibility Principle (Fundamentals S6), User handles identity while BalanceSheet handles financial state.

class User:
    """A registered user in the Splitwise system."""

    def __init__(self, user_id: str, name: str, email: str,
                 phone: str) -> None:
        self.user_id = user_id
        self.name = name
        self.email = email
        self.phone = phone
        self.balance_sheet = BalanceSheet()  # Composition

    def get_balance(self, other_user_id: str) -> float:
        return self.balance_sheet.get_balance(other_user_id)

    def get_net_balance(self) -> float:
        return self.balance_sheet.get_net_balance()

    def __repr__(self) -> str:
        return f"User({self.name})"
public class User {
    private final String userId;
    private final String name;
    private final String email;
    private final String phone;
    private final BalanceSheet balanceSheet;  // Composition

    public User(String userId, String name, String email, String phone) {
        this.userId = userId;
        this.name = name;
        this.email = email;
        this.phone = phone;
        this.balanceSheet = new BalanceSheet();
    }

    public String getUserId() { return userId; }
    public String getName() { return name; }
    public String getEmail() { return email; }
    public BalanceSheet getBalanceSheet() { return balanceSheet; }

    public double getBalance(String otherUserId) {
        return balanceSheet.getBalance(otherUserId);
    }

    public double getNetBalance() {
        return balanceSheet.getNetBalance();
    }

    @Override
    public String toString() {
        return "User(" + name + ")";
    }
}

Expense — The Core Domain Entity

An Expense records who paid, how much, the computed splits, and which strategy was used. It composes its Split objects — they have no meaning outside the expense.

from datetime import datetime
from typing import List
import uuid


class Expense:
    """A single expense record in the system."""

    def __init__(self, payer: User, amount: float,
                 description: str, splits: List[Split],
                 strategy: SplitStrategy) -> None:
        self.expense_id = str(uuid.uuid4())
        self.payer = payer
        self.amount = amount
        self.description = description
        self.splits = splits            # Composition — owned by this expense
        self.strategy = strategy
        self.created_at = datetime.now()

    def get_splits(self) -> List[Split]:
        return list(self.splits)

    def __repr__(self) -> str:
        return (f"Expense('{self.description}', amount={self.amount:.2f}, "
                f"payer={self.payer.name})")
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.Collections;

public class Expense {
    private final String expenseId;
    private final User payer;
    private final double amount;
    private final String description;
    private final List<Split> splits;  // Composition
    private final SplitStrategy strategy;
    private final LocalDateTime createdAt;

    public Expense(User payer, double amount, String description,
                   List<Split> splits, SplitStrategy strategy) {
        this.expenseId = UUID.randomUUID().toString();
        this.payer = payer;
        this.amount = amount;
        this.description = description;
        this.splits = splits;
        this.strategy = strategy;
        this.createdAt = LocalDateTime.now();
    }

    public String getExpenseId() { return expenseId; }
    public User getPayer() { return payer; }
    public double getAmount() { return amount; }
    public String getDescription() { return description; }
    public SplitStrategy getStrategy() { return strategy; }

    public List<Split> getSplits() {
        return Collections.unmodifiableList(splits);
    }

    @Override
    public String toString() {
        return String.format("Expense('%s', amount=%.2f, payer=%s)",
                             description, amount, payer.getName());
    }
}

Group — Organizing Users and Expenses

A Group holds its members (association) and its expenses (composition). It provides methods to add members and to add or remove its expenses; ExpenseService.get_expense_history() reads a group's list for a user's history in that group (R9).

from typing import List
import uuid


class Group:
    """A group of users sharing expenses."""

    def __init__(self, name: str) -> None:
        self.group_id = str(uuid.uuid4())
        self.name = name
        self._members: List[User] = []
        self._expenses: List[Expense] = []

    def add_member(self, user: User) -> None:
        if user not in self._members:
            self._members.append(user)

    def add_expense(self, expense: Expense) -> None:
        self._expenses.append(expense)

    def remove_expense(self, expense: Expense) -> None:
        self._expenses.remove(expense)

    @property
    def members(self) -> List[User]:
        return list(self._members)

    @property
    def expenses(self) -> List[Expense]:
        return list(self._expenses)

    def __repr__(self) -> str:
        return f"Group('{self.name}', members={len(self._members)})"
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.UUID;

public class Group {
    private final String groupId;
    private final String name;
    private final List<User> members = new ArrayList<>();
    private final List<Expense> expenses = new ArrayList<>();

    public Group(String name) {
        this.groupId = UUID.randomUUID().toString();
        this.name = name;
    }

    public void addMember(User user) {
        if (!members.contains(user)) {
            members.add(user);
        }
    }

    public void addExpense(Expense expense) {
        expenses.add(expense);
    }

    public void removeExpense(Expense expense) {
        expenses.remove(expense);
    }

    public String getGroupId() { return groupId; }
    public String getName() { return name; }

    public List<User> getMembers() {
        return Collections.unmodifiableList(members);
    }

    public List<Expense> getExpenses() {
        return Collections.unmodifiableList(expenses);
    }
}

ExpenseService — The Orchestrator

The ExpenseService coordinates the entire workflow: it delegates split calculation to the strategy, creates the expense, updates balances bidirectionally, and supports settle-up and undo operations. It also keeps every expense it creates, so it can answer expense history (R9): a user's expenses in one group, or across all groups. settle_up() accepts only a positive whole number of cents, and undo_expense() checks that the expense is still recorded (and in the group it is given) before it reverses anything — so a second undo is refused instead of corrupting the balances. This is the entry point for all expense-related operations.

from typing import List, Optional


class ExpenseService:
    """Orchestrates expense creation, balance updates, and settlements."""

    def __init__(self) -> None:
        self._expenses: List[Expense] = []  # every expense, in creation order (R9)

    def add_expense(
        self,
        group: Optional[Group],
        payer: User,
        amount: float,
        description: str,
        participants: List[User],
        strategy: SplitStrategy,
        shares: Optional[List[float]] = None
    ) -> Expense:
        """Create an expense and update all affected balances."""
        if shares is None:
            shares = []

        # Step 1: Delegate split calculation to strategy
        splits = strategy.split(amount, participants, shares)

        # Step 2: Create the expense
        expense = Expense(payer, amount, description, splits, strategy)

        # Step 3: Update balances for each non-payer participant
        for split in splits:
            if split.user.user_id != payer.user_id:
                # Participant owes the payer
                split.user.balance_sheet.update_balance(
                    payer.user_id, split.amount
                )
                # Payer is owed by the participant
                payer.balance_sheet.update_balance(
                    split.user.user_id, -split.amount
                )

        # Step 4: Add to group if provided
        if group is not None:
            group.add_expense(expense)

        # Step 5: Record it for expense history (R9)
        self._expenses.append(expense)
        return expense

    def settle_up(self, payer: User, payee: User,
                  amount: float) -> None:
        """Record a payment from payer to payee, reducing debt."""
        if SplitStrategy.to_cents(amount) <= 0:
            raise ValueError("A payment must be a positive amount")
        # Payer's debt to payee decreases
        payer.balance_sheet.update_balance(payee.user_id, -amount)
        # Payee's credit from payer decreases
        payee.balance_sheet.update_balance(payer.user_id, amount)

    def undo_expense(self, expense: Expense,
                     group: Optional[Group] = None) -> None:
        """Reverse an expense — undo all balance changes."""
        # Check first: reversing an expense twice would corrupt the balances
        if expense not in self._expenses:
            raise ValueError("The expense was never added, or is already undone")
        if group is not None and expense not in group.expenses:
            raise ValueError(f"The expense is not in group '{group.name}'")
        payer = expense.payer
        for split in expense.splits:
            if split.user.user_id != payer.user_id:
                # Reverse: participant's debt to payer
                split.user.balance_sheet.update_balance(
                    payer.user_id, -split.amount
                )
                # Reverse: payer's credit from participant
                payer.balance_sheet.update_balance(
                    split.user.user_id, split.amount
                )
        if group is not None:
            group.remove_expense(expense)
        self._expenses.remove(expense)

    def get_expense_history(self, user: User,
                            group: Optional[Group] = None) -> List[Expense]:
        """R9: the expenses a user paid or shares in, oldest first —
        in one group, or across all groups (and none) if group is None."""
        in_scope = group.expenses if group is not None else self._expenses
        return [e for e in in_scope
                if e.payer.user_id == user.user_id
                or any(s.user.user_id == user.user_id for s in e.splits)]
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

public class ExpenseService {
    // every expense, in creation order (R9)
    private final List<Expense> expenses = new ArrayList<>();

    public Expense addExpense(Group group, User payer, double amount,
                              String description, List<User> participants,
                              SplitStrategy strategy, List<Double> shares) {
        // Step 1: Delegate split calculation to strategy
        List<Split> splits = strategy.split(amount, participants, shares);

        // Step 2: Create the expense
        Expense expense = new Expense(payer, amount, description,
                                      splits, strategy);

        // Step 3: Update balances for each non-payer participant
        for (Split split : splits) {
            if (!split.getUser().getUserId().equals(payer.getUserId())) {
                // Participant owes the payer
                split.getUser().getBalanceSheet()
                    .updateBalance(payer.getUserId(), split.getAmount());
                // Payer is owed by the participant
                payer.getBalanceSheet()
                    .updateBalance(split.getUser().getUserId(),
                                   -split.getAmount());
            }
        }

        // Step 4: Add to group if provided
        if (group != null) {
            group.addExpense(expense);
        }

        // Step 5: Record it for expense history (R9)
        expenses.add(expense);
        return expense;
    }

    public void settleUp(User payer, User payee, double amount) {
        if (SplitStrategy.toCents(amount) <= 0) {
            throw new IllegalArgumentException("A payment must be a positive amount");
        }
        payer.getBalanceSheet().updateBalance(payee.getUserId(), -amount);
        payee.getBalanceSheet().updateBalance(payer.getUserId(), amount);
    }

    public void undoExpense(Expense expense, Group group) {
        // Check first: reversing an expense twice would corrupt the balances
        if (!expenses.contains(expense)) {
            throw new IllegalArgumentException(
                "The expense was never added, or is already undone");
        }
        if (group != null && !group.getExpenses().contains(expense)) {
            throw new IllegalArgumentException(
                "The expense is not in group '" + group.getName() + "'");
        }
        User payer = expense.getPayer();
        for (Split split : expense.getSplits()) {
            if (!split.getUser().getUserId().equals(payer.getUserId())) {
                split.getUser().getBalanceSheet()
                    .updateBalance(payer.getUserId(), -split.getAmount());
                payer.getBalanceSheet()
                    .updateBalance(split.getUser().getUserId(),
                                   split.getAmount());
            }
        }
        if (group != null) {
            group.removeExpense(expense);
        }
        expenses.remove(expense);
    }

    // R9: the expenses a user paid or shares in, oldest first —
    // in one group, or across all groups (and none) if group is null
    public List<Expense> getExpenseHistory(User user, Group group) {
        List<Expense> inScope = (group != null) ? group.getExpenses() : expenses;
        List<Expense> history = new ArrayList<>();
        for (Expense e : inScope) {
            boolean involved = e.getPayer().getUserId().equals(user.getUserId());
            for (Split s : e.getSplits()) {
                if (s.getUser().getUserId().equals(user.getUserId())) {
                    involved = true;
                }
            }
            if (involved) {
                history.add(e);
            }
        }
        return Collections.unmodifiableList(history);
    }
}

Usage Example

Let's see the complete system in action with a realistic trip scenario — three friends sharing multiple expenses with different split strategies.

def main():
    # Create users
    alice = User("u1", "Alice", "alice@email.com", "555-0001")
    bob = User("u2", "Bob", "bob@email.com", "555-0002")
    charlie = User("u3", "Charlie", "charlie@email.com", "555-0003")

    # Create a group
    trip = Group("Weekend Trip")
    trip.add_member(alice)
    trip.add_member(bob)
    trip.add_member(charlie)

    service = ExpenseService()

    # Expense 1: Alice pays $120 for dinner, split equally
    e1 = service.add_expense(
        group=trip, payer=alice, amount=120.00,
        description="Dinner",
        participants=[alice, bob, charlie],
        strategy=EqualSplitStrategy()
    )
    print(f"Added: {e1}")
    # Bob owes Alice $40, Charlie owes Alice $40

    # Expense 2: Bob pays $90 for gas, exact split
    e2 = service.add_expense(
        group=trip, payer=bob, amount=90.00,
        description="Gas",
        participants=[alice, bob, charlie],
        strategy=ExactSplitStrategy(),
        shares=[20.00, 40.00, 30.00]
    )
    print(f"Added: {e2}")
    # Alice owes Bob $20, Charlie owes Bob $30

    # Expense 3: Charlie pays $200 for hotel, percentage split
    e3 = service.add_expense(
        group=trip, payer=charlie, amount=200.00,
        description="Hotel",
        participants=[alice, bob, charlie],
        strategy=PercentageSplitStrategy(),
        shares=[50.0, 30.0, 20.0]
    )
    print(f"Added: {e3}")
    # Alice owes Charlie $100, Bob owes Charlie $60

    # Check balances
    print(f"\nAlice's net balance: ${alice.get_net_balance():.2f}")
    print(f"Bob's net balance: ${bob.get_net_balance():.2f}")
    print(f"Charlie's net balance: ${charlie.get_net_balance():.2f}")

    print()
    for user in (alice, bob, charlie):
        balances = sorted(user.balance_sheet.get_all_balances().items())
        print(f"{user.name}'s detailed balances: "
              + ", ".join(f"{uid} {amount:.2f}" for uid, amount in balances))

    # Settle up: Bob pays Alice $20
    service.settle_up(payer=bob, payee=alice, amount=20.00)
    print(f"\nAfter Bob pays Alice $20:")
    print(f"Bob owes Alice: ${bob.get_balance(alice.user_id):.2f}")

    # Undo expense 3
    service.undo_expense(e3, trip)
    print(f"\nAfter undoing hotel expense:")
    print(f"Alice's net balance: ${alice.get_net_balance():.2f}")
    print(f"Group expenses: {len(trip.expenses)}")

    # Expense history (R9): Bob's expenses, oldest first
    print(f"\nBob's expense history: {service.get_expense_history(bob)}")


if __name__ == "__main__":
    main()
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
import java.util.TreeMap;
import java.util.ArrayList;

public class SplitwiseDemo {
    public static void main(String[] args) {
        // Create users
        User alice = new User("u1", "Alice", "alice@email.com", "555-0001");
        User bob = new User("u2", "Bob", "bob@email.com", "555-0002");
        User charlie = new User("u3", "Charlie", "charlie@email.com", "555-0003");

        // Create a group
        Group trip = new Group("Weekend Trip");
        trip.addMember(alice);
        trip.addMember(bob);
        trip.addMember(charlie);

        ExpenseService service = new ExpenseService();
        List<User> everyone = Arrays.asList(alice, bob, charlie);

        // Expense 1: Alice pays $120 for dinner, split equally
        Expense e1 = service.addExpense(trip, alice, 120.00, "Dinner",
            everyone, new EqualSplitStrategy(), Collections.emptyList());
        System.out.println("Added: " + e1);

        // Expense 2: Bob pays $90 for gas, exact split
        Expense e2 = service.addExpense(trip, bob, 90.00, "Gas",
            everyone, new ExactSplitStrategy(),
            Arrays.asList(20.0, 40.0, 30.0));
        System.out.println("Added: " + e2);

        // Expense 3: Charlie pays $200 for hotel, percentage split
        Expense e3 = service.addExpense(trip, charlie, 200.00, "Hotel",
            everyone, new PercentageSplitStrategy(),
            Arrays.asList(50.0, 30.0, 20.0));
        System.out.println("Added: " + e3);

        // Check balances
        System.out.printf("%nAlice's net balance: $%.2f%n",
                          alice.getNetBalance());
        System.out.printf("Bob's net balance: $%.2f%n",
                          bob.getNetBalance());
        System.out.printf("Charlie's net balance: $%.2f%n",
                          charlie.getNetBalance());

        System.out.println();
        for (User user : List.of(alice, bob, charlie)) {
            List<String> balances = new ArrayList<>();
            new TreeMap<>(user.getBalanceSheet().getAllBalances()).forEach((uid, amount) ->
                balances.add(String.format("%s %.2f", uid, amount)));
            System.out.println(user.getName() + "'s detailed balances: "
                               + String.join(", ", balances));
        }

        // Settle up: Bob pays Alice $20
        service.settleUp(bob, alice, 20.00);
        System.out.printf("%nAfter Bob pays Alice $20:%n");
        System.out.printf("Bob owes Alice: $%.2f%n",
                          bob.getBalance(alice.getUserId()));

        // Undo expense 3
        service.undoExpense(e3, trip);
        System.out.printf("%nAfter undoing hotel expense:%n");
        System.out.printf("Alice's net balance: $%.2f%n",
                          alice.getNetBalance());
        System.out.printf("Group expenses: %d%n",
                          trip.getExpenses().size());

        // Expense history (R9): Bob's expenses, oldest first
        System.out.println("\nBob's expense history: "
                           + service.getExpenseHistory(bob, null));
    }
}