I'll Be Backend
Principles · C++

Imperative to declarative: loops into pipelines

Say what you want from a list, and let the pipeline do the walking.

12 steps4 chapters~5 min at 1.25×#declarative code#collection pipeline#streams#loops
Language
The lesson plays right here. Pause anywhere, step back, or jump to a step below. Watch the C++ video on YouTube Code on GitHub

Watch the narrated video

Every step

Problem

Steps 1–4

Refactor

Steps 5–8

Payoff

Steps 9–10

Recap

Steps 11–12

The code: before and after

Before

struct Order {
    std::string customer;
    std::string status;
    int total;
};

class SalesReport {
public:
    int shippedRevenue(const std::vector<Order>& orders) const {
        int sum = 0;
        for (const Order& o : orders) {
            if (o.status == "SHIPPED") sum += o.total;
        }
        return sum;
    }

    std::vector<std::string> topCustomers(
            const std::vector<Order>& orders) const {
        std::vector<Order> shipped;
        for (const Order& o : orders) {
            if (o.status == "SHIPPED") shipped.push_back(o);
        }
        std::ranges::sort(shipped, std::greater{}, &Order::total);
        std::vector<std::string> names;
        for (const Order& o : shipped) {
            if (names.size() == 3) break;
            if (std::ranges::find(names, o.customer) == names.end())
                names.push_back(o.customer);
        }
        return names;
    }
};

struct DailyDigest {
    static void run(const SalesReport& report) {
        std::vector<Order> orders = {
            {"ana@shop.com", "SHIPPED", 120},
            {"qa@test.shop", "SHIPPED", 999},
            {"bo@shop.com", "PENDING", 80},
            {"cy@shop.com", "SHIPPED", 45},
            {"ana@shop.com", "SHIPPED", 60}};
        std::cout << report.shippedRevenue(orders) << '\n';
        for (const std::string& name : report.topCustomers(orders))
            std::cout << name << '\n';
    }
};

After

struct Order {
    std::string customer;
    std::string status;
    int total;
};

class SalesReport {
public:
    int shippedRevenue(const std::vector<Order>& orders) const {
        auto totals = orders
            | std::views::filter(countsAsSale)
            | std::views::transform(&Order::total);
        return std::accumulate(totals.begin(), totals.end(), 0);
    }

    std::vector<std::string> topCustomers(
            const std::vector<Order>& orders) const {
        std::vector<Order> shipped;
        std::ranges::copy_if(orders, std::back_inserter(shipped),
            countsAsSale);
        std::ranges::sort(shipped, std::greater{}, &Order::total);
        std::unordered_set<std::string> seen;
        std::vector<std::string> names;
        std::ranges::copy(shipped
            | std::views::transform(&Order::customer)
            | std::views::filter([&seen](const std::string& c) {
                  return seen.insert(c).second;
              })
            | std::views::take(3),
            std::back_inserter(names));
        return names;
    }

private:
    static bool countsAsSale(const Order& o) {
        return o.status == "SHIPPED"
            && !o.customer.ends_with("@test.shop");
    }
};

struct DailyDigest {
    static void run(const SalesReport& report) {
        std::vector<Order> orders = {
            {"ana@shop.com", "SHIPPED", 120},
            {"qa@test.shop", "SHIPPED", 999},
            {"bo@shop.com", "PENDING", 80},
            {"cy@shop.com", "SHIPPED", 45},
            {"ana@shop.com", "SHIPPED", 60}};
        std::cout << report.shippedRevenue(orders) << '\n';
        for (const std::string& name : report.topCustomers(orders))
            std::cout << name << '\n';
    }
};

Transcript, step by step

Problem

Step 1: A sales report in loops Before

This sales report works on a vector of orders, and each order has a customer email, a status and a total. Shipped revenue walks the vector and adds the total of every shipped order to a running sum. Top customers copies 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 vector 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 find 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 a view Replace Loop with Pipeline

Shipped revenue now pipes the orders through two range views. Filter keeps the shipped ones, transform takes each total, and accumulate adds them up from zero. The running sum is gone, because accumulate keeps that total for you, and the digest still prints twelve twenty-four.

Step 6: Copy if, then sort Replace Loop with Pipeline

In top customers, the first loop becomes one call to copy if, with the status test as its condition. Shipped stays a vector, because a view never stores anything and sort needs the orders in one place. Nobody writes that fill loop 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 becomes a pipeline over shipped, and copy writes its names into the result. Transform takes each order's customer, the filter drops the repeats, and take three stops after three names. The standard library has no view 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 find 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 lambdas, so we extract it into one private function called counts as sale. Both callers pass it by name, first the filter view in shipped revenue and then copy if 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 accumulate here, the hand-filled vector became copy if here, and the break and the find 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 find, and breaks at three. On the right, each method is a chain of views and range algorithms, 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 a fold. 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 range views already work this way, because they're lazy, so take stops pulling elements early, the way a break does.