Imperative to declarative: loops into pipelines
Say what you want from a list, and let the pipeline do the walking.
Watch the narrated video
Every step
Problem
Steps 1–4Refactor
Steps 5–8Payoff
Steps 9–10Recap
Steps 11–12The code: before and after
Before
record Order(string Customer, string Status, int Total);
class SalesReport
{
public int ShippedRevenue(List<Order> orders)
{
int sum = 0;
foreach (var o in orders)
{
if (o.Status == "SHIPPED") sum += o.Total;
}
return sum;
}
public List<string> TopCustomers(List<Order> orders)
{
var shipped = new List<Order>();
foreach (var o in orders)
{
if (o.Status == "SHIPPED") shipped.Add(o);
}
shipped.Sort((a, b) => b.Total.CompareTo(a.Total));
var names = new List<string>();
foreach (var o in shipped)
{
if (names.Count == 3) break;
if (!names.Contains(o.Customer)) names.Add(o.Customer);
}
return names;
}
}
class DailyDigest
{
public static void Run(SalesReport report)
{
List<Order> orders =
[
new("ana@shop.com", "SHIPPED", 120),
new("qa@test.shop", "SHIPPED", 999),
new("bo@shop.com", "PENDING", 80),
new("cy@shop.com", "SHIPPED", 45),
new("ana@shop.com", "SHIPPED", 60),
];
Console.WriteLine(report.ShippedRevenue(orders));
Console.WriteLine(string.Join(", ", report.TopCustomers(orders)));
}
}After
record Order(string Customer, string Status, int Total);
class SalesReport
{
public int ShippedRevenue(List<Order> orders)
{
return orders
.Where(CountsAsSale)
.Select(o => o.Total)
.Sum();
}
public List<string> TopCustomers(List<Order> orders)
{
return orders
.Where(CountsAsSale)
.OrderByDescending(o => o.Total)
.Select(o => o.Customer)
.Distinct()
.Take(3)
.ToList();
}
private static bool CountsAsSale(Order o)
{
return o.Status == "SHIPPED"
&& !o.Customer.EndsWith("@test.shop");
}
}
class DailyDigest
{
public static void Run(SalesReport report)
{
List<Order> orders =
[
new("ana@shop.com", "SHIPPED", 120),
new("qa@test.shop", "SHIPPED", 999),
new("bo@shop.com", "PENDING", 80),
new("cy@shop.com", "SHIPPED", 45),
new("ana@shop.com", "SHIPPED", 60),
];
Console.WriteLine(report.ShippedRevenue(orders));
Console.WriteLine(string.Join(", ", report.TopCustomers(orders)));
}
}Transcript, step by step
Problem
Step 1: A sales report in loops Before
This sales report works on a list of orders, and each order has a customer email, a status and a total. Shipped Revenue walks the list and adds the total of every shipped order to a running sum. Top Customers copies the shipped orders into a list, sorts them by total, and walks them again to collect three different customers. The daily digest builds today's orders and prints both results. One of those orders comes from a test account at test dot shop, and it's the biggest order of the day.
Step 2: Leave out test orders Code smell
Finance says test orders, from customers at test dot shop, must not count in either number. So the check goes into the if in Shipped Revenue, and into the if in the first loop of Top Customers. This code is imperative, because it spells out how to walk the list step by step, so you have to replay the loop in your head to learn what it's for. You can see it in the running sum here, the temporary shipped list here, and the break and the Contains check here.
Step 3: The rule, twice Code smell
The rule for what counts as a sale is now written twice, so the next rule has to be found and added twice too. And in Top Customers, the filter, the ranking, the repeat check and the stop at three are tangled across two loops. So you replay both loops line by line to see which one decides what counts as a sale, and where a new condition belongs.
Step 4: Back it out, then pipelines Plan
Let's back that change out. Declarative code says what you want, so we'll turn each loop into a collection pipeline, a chain of operations where each one has one job, and add the rule after that.
Refactor
Step 5: Shipped revenue in LINQ Replace Loop with Pipeline
Shipped Revenue now returns one LINQ pipeline over the orders. Where keeps the shipped ones, Select takes each total, and Sum adds them up. The running sum is gone, because Sum keeps that total for you, and the digest still prints twelve twenty-four.
Step 6: Filter and sort in one chain Replace Loop with Pipeline
In Top Customers, the first loop and the sort become one pipeline. Where keeps the shipped orders, Order By Descending ranks them by total from high to low, and To List collects the result. Nobody fills a temporary list by hand anymore, and the second loop still reads from shipped, so the output stays the same.
Step 7: The second loop joins Replace Loop with Pipeline
Now the second loop joins the same pipeline. Select takes each order's customer, Distinct drops the repeats, and Take three stops after three names. The output doesn't change, because Distinct hands back each name the first time it meets it, as the Contains check did, and Take three does what the break did.
Step 8: Name the sale rule Extract Function
The status test now sits in two Where calls, so we extract it into one method called Counts As Sale. Both pipelines pass it by name as a method group, first in Shipped Revenue and then in Top Customers. Now the diagram shows both methods asking one place what a sale is.
Payoff
Step 9: Test orders, one edit Payoff
Now Finance's rule goes in again, and this time it's one edit inside Counts As Sale. Neither pipeline changed, because both of them ask Counts As Sale and don't care what it checks. So the digest now prints two twenty-five, with Ana and Cy as the top customers.
Step 10: Why it was easy Payoff
The running sum became Sum here, the temporary list became Order By Descending here, and the break and the Contains check became Distinct and Take here. Top Customers is now four jobs on four lines, so you can see at a glance that a new sale rule belongs in the Where. Giving that rule one home for both pipelines came from Extract Function, and the pipelines made the spot easy to find.
Recap
Step 11: Where we started, where we ended Before / after
On the left, Shipped Revenue keeps a running sum, and Top Customers fills a temporary list, checks Contains, and breaks at three. On the right, each method is one pipeline, and each line in it does one job. And Counts As Sale holds the rule for both of them, so Finance's next rule is one edit too.
Step 12: When to reach for it Takeaways
Reach for a pipeline when a loop filters, transforms or totals a collection, and you want each job readable on its own line. Skip it when each step depends on the one before, like a running balance that stops at the first overdraft, because the loop says that more plainly than Aggregate. You'll spot it by a temporary list filled in a loop, a running total, or a break or flag that stops early. LINQ itself works this way, because it runs lazily, and Take stops pulling orders once it has enough, the way a break does.