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
struct Order {
customer: &'static str,
status: &'static str,
total: i32,
}
struct SalesReport;
impl SalesReport {
fn shipped_revenue(&self, orders: &[Order]) -> i32 {
let mut sum = 0;
for o in orders {
if o.status == "SHIPPED" {
sum += o.total;
}
}
sum
}
fn top_customers(&self, orders: &[Order]) -> Vec<&str> {
let mut shipped = Vec::new();
for o in orders {
if o.status == "SHIPPED" {
shipped.push(o);
}
}
shipped.sort_by(|a, b| b.total.cmp(&a.total));
let mut names = Vec::new();
for o in shipped {
if names.len() == 3 {
break;
}
if !names.contains(&o.customer) {
names.push(o.customer);
}
}
names
}
}
fn daily_digest(report: &SalesReport) {
let orders = [
Order { customer: "ana@shop.com", status: "SHIPPED", total: 120 },
Order { customer: "qa@test.shop", status: "SHIPPED", total: 999 },
Order { customer: "bo@shop.com", status: "PENDING", total: 80 },
Order { customer: "cy@shop.com", status: "SHIPPED", total: 45 },
Order { customer: "ana@shop.com", status: "SHIPPED", total: 60 },
];
println!("{}", report.shipped_revenue(&orders));
println!("{:?}", report.top_customers(&orders));
}After
struct Order {
customer: &'static str,
status: &'static str,
total: i32,
}
struct SalesReport;
impl SalesReport {
fn shipped_revenue(&self, orders: &[Order]) -> i32 {
orders
.iter()
.filter(|o| counts_as_sale(o))
.map(|o| o.total)
.sum()
}
fn top_customers(&self, orders: &[Order]) -> Vec<&str> {
let mut shipped: Vec<&Order> = orders
.iter()
.filter(|o| counts_as_sale(o))
.collect();
shipped.sort_by(|a, b| b.total.cmp(&a.total));
let mut seen = HashSet::new();
shipped
.into_iter()
.map(|o| o.customer)
.filter(|c| seen.insert(*c))
.take(3)
.collect()
}
}
fn counts_as_sale(o: &Order) -> bool {
o.status == "SHIPPED" && !o.customer.ends_with("@test.shop")
}
fn daily_digest(report: &SalesReport) {
let orders = [
Order { customer: "ana@shop.com", status: "SHIPPED", total: 120 },
Order { customer: "qa@test.shop", status: "SHIPPED", total: 999 },
Order { customer: "bo@shop.com", status: "PENDING", total: 80 },
Order { customer: "cy@shop.com", status: "SHIPPED", total: 45 },
Order { customer: "ana@shop.com", status: "SHIPPED", total: 60 },
];
println!("{}", report.shipped_revenue(&orders));
println!("{:?}", report.top_customers(&orders));
}Transcript, step by step
Problem
Step 1: A sales report in loops Before
This sales report works on a slice of orders, and each order has a customer email, a status and a total. Shipped revenue walks the slice and adds the total of every shipped order to a running sum. Top customers pushes the shipped orders into a vector, 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 result. 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 slice 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 vector 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 as an iterator Replace Loop with Pipeline
Shipped revenue now takes an iterator over the orders and chains three steps onto it. Filter keeps the shipped ones, map 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, collect, then sort Replace Loop with Pipeline
In top customers, the first loop becomes a filter with the status test, and collect gathers the shipped orders into a vector. Rust's iterators have no sort, because sorting needs every order in one place, so sort by stays a call on the collected vector. 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 becomes a pipeline over shipped, and collect builds the vector that top customers returns. Map takes each order's customer, the filter drops the repeats, and take three stops after three names. The standard library has no adapter that drops repeats and keeps the order, so this filter holds state in a seen set, and insert returns true only the first time it meets a name. So the output doesn't change, because the filter keeps a name the first time, 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 closures, so we extract it into one function called counts as sale. Both filters call it by name, 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 method 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 hand-filled vector became filter and collect here, and the break and the contains check became the seen filter and take three here. Top customers now gives each job its own line, filter, sort, drop repeats and take three, so you can see at a glance that a new sale rule belongs in the filter. Giving that rule one home for both methods 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 vector by hand, checks with contains, and breaks at three. On the right, each method is a chain of iterator adapters, 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 an iterator chain. You'll spot it by a temporary vector filled in a loop, a running total, or a break or flag that stops early. The standard iterator adapters already work this way, because they're lazy, so take stops pulling items early, the way a break does.