Practical .NET · Lesson 10

Separate calculation from output

Compute in one place, print in another.

How it works

Summarize only calculates: it takes orders and returns a record with the paid total and the count of unpaid orders. It never touches the console, so it is easy to test with any list. The last lines decide how to show the result. Changing the wording of the report does not change the calculation.

A working example

var orders = new[] { new Order("a", 10m, true), new Order("b", 4m, false), new Order("c", -3m, true) };

var summary = Summarize(orders);
Console.WriteLine($"paid {summary.Paid}");
Console.WriteLine($"unpaid orders {summary.Unpaid}");

static (decimal Paid, int Unpaid) Summarize(IEnumerable<Order> orders) =>
    (orders.Where(o => o.IsPaid).Sum(o => o.Amount), orders.Count(o => !o.IsPaid));

Expected output

paid 7
unpaid orders 1
Try this
A method that returns a value is easier to check than one that prints.