Skip to content

On Your Own: An Expense Ledger

The Course
•
45 min study

This is the real test of the week: a new problem, with no steps to follow, and hints closed for as long as you can stand. It is a whole program, a store, a fake and a set of checks, so expect it to take an hour or more; the 45-minute estimate assumes the week went smoothly. Don't copy the tracker. Reuse its ideas: records for data, a class that returns Result values, LINQ for reports, and an interface for storage so you can test it.

The brief

Commands arrive one per line.

  • spend <category> <amount> <note> records an expense. The category is one word. The amount is a positive decimal, at most 10000. The note can contain spaces, and is 1 to 40 characters.
  • undo removes the latest expense, or prints Error: nothing to undo.
  • report prints each category with its total, largest first, then ties by name, as food: 12.50, and finally a line such as Total: 20.00. Use two decimal places.
  • save and load use an IStore, passed into the ledger's constructor, not a file name. The real one is JSON, and your checks use a fake. A failed load leaves the expenses unchanged.

A bad line prints Error: and the reason, and later lines still run.

Acceptance example, for spend food 12.50 lunch, spend bus 7.50 to town, spend food -1 refund, report, undo, report:

  • Error: amount must be above 0 and at most 10000 for the refund
  • First report: food: 12.50, bus: 7.50, Total: 20.00
  • Second report: food: 12.50, Total: 12.50

Warm up: money and formats

Predict what happens to each amount. Which formatting choice suits this brief?

decimal and culture C#
using System.Globalization;

foreach (string text in new[] { "12.5", "1,000", "abc" })
{
    bool good = decimal.TryParse(text, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal amount);
    Console.WriteLine(good ? amount.ToString("F2", CultureInfo.InvariantCulture) : "bad");
}

Console.WriteLine(0.1m + 0.2m == 0.3m);
Console.WriteLine(0.1 + 0.2 == 0.3);
Check your prediction
Text
12.50
1000.00
bad
True
False

decimal stores base-10 fractions exactly, so it suits money. NumberStyles.Number allows thousands separators, and it's worth deciding whether your brief wants that.

Build it yourself

Exercise

The expense ledger

Implement the whole brief in one file: an Expense record, an IStore interface with a JSON implementation and a fake, a Ledger class, a command handler, and the input loop. Add checks at the top for the amount boundaries (0, 0.01, 10000, 10000.01), a too-long note, undo on an empty ledger, a failed load, and report sorting with a tie.

When it works, it prints:

Text
Spent 12.50 on food
Spent 7.50 on bus
Error: amount must be above 0 and at most 10000
food: 12.50
bus: 7.50
Total: 20.00
Undid to town
food: 12.50
Total: 12.50
Saved 1
Undid lunch
Total: 0.00
Loaded 1
food: 12.50
Total: 12.50
Your workspace C#
#nullable enable

string? line = Console.ReadLine();
Console.WriteLine(line);
spend food 12.50 lunch spend bus 7.50 to town spend food -1 refund report undo report save undo report load report
Hint 1: the idea

Totals are never stored, so undo and load can't make them wrong. Every report works from the current list of expenses.

Hint 2: a first step

Write Ledger.Spend with its rules and checks, with no input loop or storage at all. Add report next, and bring in IStore last.

Show one solution
C#
#nullable enable

using System.Globalization;
using System.Text.Json;

int failures = 0;

void Check(bool passed, string name)
{
    if (!passed)
    {
        Console.WriteLine($"FAILED: {name}");
        failures++;
    }
}

var limits = new Ledger(new FakeStore());
Check(limits.Spend("a", 0m, "n") is Fail<Expense>, "refuses 0");
Check(limits.Spend("a", 0.01m, "n") is Ok<Expense>, "accepts 0.01");
Check(limits.Spend("a", 10000m, "n") is Ok<Expense>, "accepts 10000");
Check(limits.Spend("a", 10000.01m, "n") is Fail<Expense>, "refuses over 10000");
Check(limits.Spend("a", 1m, new string('x', 41)) is Fail<Expense>, "refuses a long note");
Check(new Ledger(new FakeStore()).Undo() is Fail<Expense>, "undo on an empty ledger");

var failing = new Ledger(new FakeStore { Fails = true });
failing.Spend("a", 1m, "kept");
Check(failing.Load() is Fail<int> && failing.Expenses.Count == 1, "a failed load keeps the expenses");

var tie = new Ledger(new FakeStore());
tie.Spend("b", 5m, "n");
tie.Spend("a", 5m, "n");
Check(tie.Totals().First().Category == "a", "ties sort by name");

var commands = new LedgerCommands(new Ledger(new JsonStore("ledger.json")));
string? line;
while ((line = Console.ReadLine()) is not null)
{
    foreach (string output in commands.Execute(line))
    {
        Console.WriteLine(output);
    }
}

record Expense(string Category, decimal Amount, string Note);

interface IStore
{
    List<Expense> Load();
    void Save(IReadOnlyList<Expense> expenses);
}

class JsonStore(string path) : IStore
{
    public List<Expense> Load() => JsonSerializer.Deserialize<List<Expense>>(File.ReadAllText(path)) ?? new List<Expense>();

    public void Save(IReadOnlyList<Expense> expenses)
    {
        File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(expenses));
        File.Move(path + ".tmp", path, overwrite: true);
    }
}

class FakeStore : IStore
{
    private List<Expense> saved = new();

    public bool Fails { get; init; }

    public List<Expense> Load() => Fails ? throw new IOException("disk") : new List<Expense>(saved);

    public void Save(IReadOnlyList<Expense> expenses)
    {
        saved = new List<Expense>(expenses);
    }
}

class Ledger(IStore store)
{
    private readonly List<Expense> expenses = new();

    public IReadOnlyList<Expense> Expenses => expenses;

    public Result<Expense> Spend(string category, decimal amount, string note)
    {
        if (amount <= 0m || amount > 10000m)
        {
            return new Fail<Expense>("amount must be above 0 and at most 10000");
        }
        string trimmed = note.Trim();
        if (trimmed.Length == 0 || trimmed.Length > 40)
        {
            return new Fail<Expense>("note must be 1 to 40 characters");
        }
        var expense = new Expense(category, amount, trimmed);
        expenses.Add(expense);
        return new Ok<Expense>(expense);
    }

    public Result<Expense> Undo()
    {
        if (expenses.Count == 0)
        {
            return new Fail<Expense>("nothing to undo");
        }
        Expense last = expenses[^1];
        expenses.RemoveAt(expenses.Count - 1);
        return new Ok<Expense>(last);
    }

    public IEnumerable<(string Category, decimal Total)> Totals()
    {
        return expenses.GroupBy(expense => expense.Category)
            .Select(group => (group.Key, group.Sum(expense => expense.Amount)))
            .OrderByDescending(row => row.Item2)
            .ThenBy(row => row.Key);
    }

    public Result<int> Save()
    {
        try
        {
            store.Save(expenses);
            return new Ok<int>(expenses.Count);
        }
        catch (IOException e)
        {
            return new Fail<int>(e.Message);
        }
    }

    public Result<int> Load()
    {
        List<Expense> loaded;
        try
        {
            loaded = store.Load();
        }
        catch (IOException e)
        {
            return new Fail<int>(e.Message);
        }
        catch (JsonException e)
        {
            return new Fail<int>(e.Message);
        }
        expenses.Clear();
        expenses.AddRange(loaded);
        return new Ok<int>(expenses.Count);
    }
}

class LedgerCommands(Ledger ledger)
{
    private static string Money(decimal value) => value.ToString("F2", CultureInfo.InvariantCulture);

    public IEnumerable<string> Execute(string line) => line.Split(' ', 4) switch
    {
        ["spend", var category, var amount, var note] => Spend(category, amount, note),
        ["undo"] => Show(ledger.Undo(), expense => $"Undid {expense.Note}"),
        ["report"] => Report(),
        ["save"] => Show(ledger.Save(), count => $"Saved {count}"),
        ["load"] => Show(ledger.Load(), count => $"Loaded {count}"),
        _ => new[] { $"Error: unknown command {line}" },
    };

    private IEnumerable<string> Spend(string category, string amount, string note)
    {
        if (!decimal.TryParse(amount, NumberStyles.Number, CultureInfo.InvariantCulture, out decimal value))
        {
            return new[] { $"Error: bad amount {amount}" };
        }
        return Show(ledger.Spend(category, value, note), expense => $"Spent {Money(expense.Amount)} on {expense.Category}");
    }

    private IEnumerable<string> Report()
    {
        var rows = ledger.Totals().Select(row => $"{row.Category}: {Money(row.Total)}").ToList();
        rows.Add($"Total: {Money(ledger.Expenses.Sum(expense => expense.Amount))}");
        return rows;
    }

    private static IEnumerable<string> Show<T>(Result<T> result, Func<T, string> success) => result switch
    {
        Ok<T> ok => new[] { success(ok.Value) },
        Fail<T> fail => new[] { $"Error: {fail.Error}" },
        _ => throw new InvalidOperationException("unknown result"),
    };
}

abstract record Result<T>;

sealed record Ok<T>(T Value) : Result<T>;

sealed record Fail<T>(string Error) : Result<T>;
Text
Spent 12.50 on food
Spent 7.50 on bus
Error: amount must be above 0 and at most 10000
food: 12.50
bus: 7.50
Total: 20.00
Undid to town
food: 12.50
Total: 12.50
Saved 1
Undid lunch
Total: 0.00
Loaded 1
food: 12.50
Total: 12.50

The ledger never touches a file itself: it talks to an IStore, so the checks run against FakeStore, which can be told to fail. Validation happens before anything changes, a failed load leaves the expenses as they were, and the JSON store saves through a temporary file, which are the week's three rules for data you can trust. If your version differs, compare it on those points rather than line by line.

Compare your design with the solution, not your text. Where did each rule go? Could you test Ledger without the console? The solution's Show helper is generic, because Spend and Load return different types of Result. It's a nice payoff for Day 2.

Was this article helpful?

Your response is saved on this device.