Skip to content

Lesson 3 of 6

Days 2 and 3: Build the Thinnest Thing That Works End to End

Build the smallest version that goes from the customer's files to a list they could use, start with a rule a person can check, and test the one rule the numbers will rest on.

7 minForward Deployed Engineering

After this lesson you will be able to build a thin end-to-end version of an idea in two days, choosing what to build properly, what to hard-code and what to test.

End to end first

By the end of day 2 you want the whole path working, however roughly: read the files, apply a rule, print a list. A rough version of everything teaches you more than a polished version of the first step, because the surprises are usually in the joins between steps.

So build in this order: the loader, the rule, the list. Then improve whichever part is weakest.

One place for the data decisions

Create loader.py. It turns the five decisions in the data note into code, and it is the only file that knows about them.

"""Read the export and apply the decisions from the data notes, in one place."""

import csv
from datetime import date, datetime

TEST_CARDS = {"M999"}


def parse_date(text):
    """The export has two date formats: 2026-03-30 and 30/03/2026."""
    if not text:
        return None
    if "/" in text:
        return datetime.strptime(text, "%d/%m/%Y").date()
    return date.fromisoformat(text)


def load_members(path="members.csv"):
    """One entry per member. A repeated row is kept once."""
    members = {}
    with open(path, newline="", encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            members.setdefault(row["member_id"], {
                "plan": row["plan"],
                "joined": parse_date(row["joined"]),
                "cancelled_on": parse_date(row["cancelled_on"]),
            })
    return members


def load_visits(members, path="visits.csv"):
    """Visit dates for each known member. Test cards and visits after cancelling are left out."""
    visits = {member_id: [] for member_id in members}
    with open(path, newline="", encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            member_id, day = row["member_id"], parse_date(row["date"])
            if member_id in TEST_CARDS or member_id not in members:
                continue
            cancelled_on = members[member_id]["cancelled_on"]
            if cancelled_on and day > cancelled_on:
                continue
            visits[member_id].append(day)
    return visits

Each decision is one visible line or two. The repeated member is kept once by setdefault. Both date forms go through parse_date. The test card is named in TEST_CARDS. The last check in load_visits covers the sixth fault, found in the exercise of lesson 2: three visits were logged after the member had cancelled, because a card goes on working until the paid month ends. Those visits say nothing about whether a member is about to leave, so they are left out.

Everything after this reads members and visits through these two functions and never opens the files directly.

Start with a rule a person can check

How do you pick the members? The membership team lead has a view from years of doing the job: people stop coming before they cancel. That is a rule, and you can test it.

A member goes on the list if they made at least four visits in the four weeks before last, and half as many or fewer in the last four weeks. The biggest fall comes first.

It is worth resisting anything cleverer at this point. A simple rule can be read by the customer, checked by hand against one member's visits, and explained on a phone call. If it passes the test in the brief, the question is answered. If it fails, you have a clear measure that a more complicated method has to beat.

Create score.py.

"""Make the call list: members whose visits have fallen by half or more.

Usage: python score.py              the list as of the day after the export ends
       python score.py 2026-03-30   the list as it would have been on that day
"""

import csv
import sys
from datetime import date, timedelta

from loader import load_members, load_visits

EXPORT_END = date(2026, 4, 27)  # the day after the last day in the export
WINDOW = 28                     # days in each of the two periods compared
LIST_SIZE = 15                  # how many calls the membership team can make in a week


def visit_counts(days, as_of):
    """Visits in the four weeks before last, and in the last four weeks, before as_of."""
    recent_start = as_of - timedelta(days=WINDOW)
    before_start = as_of - timedelta(days=2 * WINDOW)
    before = sum(1 for day in days if before_start <= day < recent_start)
    recent = sum(1 for day in days if recent_start <= day < as_of)
    return before, recent


def call_list(members, visits, as_of, size=LIST_SIZE):
    """Use only what was known before as_of. Biggest fall first."""
    rows = []
    for member_id, member in members.items():
        if member["cancelled_on"] and member["cancelled_on"] < as_of:
            continue  # already gone
        before, recent = visit_counts(visits[member_id], as_of)
        if before < 4 or recent * 2 > before:
            continue  # too few visits to judge, or no real fall
        rows.append({
            "member_id": member_id,
            "plan": member["plan"],
            "before": before,
            "recent": recent,
            "last_visit": max(day for day in visits[member_id] if day < as_of).isoformat(),
            "fall": round((before - recent) / before, 2),
        })
    rows.sort(key=lambda row: (-row["fall"], row["last_visit"], row["member_id"]))
    return rows[:size]


def main(as_of):
    members = load_members()
    rows = call_list(members, load_visits(members), as_of)
    print(f"Call list as of {as_of}: {len(rows)} members")
    print("member  plan          4 weeks before  last 4 weeks  last visit")
    for row in rows:
        print(f"{row['member_id']}    {row['plan']:<13} {row['before']:>14}  {row['recent']:>12}  {row['last_visit']}")
    with open("call_list.csv", "w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
        writer.writeheader()
        writer.writerows(rows)
    print("saved call_list.csv")


if __name__ == "__main__":
    main(date.fromisoformat(sys.argv[1]) if len(sys.argv) > 1 else EXPORT_END)

Three things in it are deliberate.

call_list takes the day as an argument, as_of, and uses only visits before that day. Today that looks unnecessary. In lesson 4 it is what makes an honest test possible.

The numbers the question does not depend on are plain constants at the top: the date the export ends, the size of the list. A real product would look them up. Here that would be a day spent on something nobody doubts.

Members with fewer than four visits in the earlier period are skipped. You cannot see a fall from two visits to one, and saying so is better than ranking noise.

Run it

python score.py
Call list as of 2026-04-27: 13 members
member  plan          4 weeks before  last 4 weeks  last visit
M101    gym and swim               5             0  2026-03-18
M120    swim                       8             1  2026-04-05
M038    gym                        7             1  2026-04-01
M077    swim                       7             1  2026-04-05
M023    gym                        7             1  2026-04-07
M107    swim                       6             1  2026-04-04
M111    gym                        6             1  2026-04-12
M015    swim                       5             1  2026-04-02
M022    gym and swim              10             2  2026-04-10
M069    gym and swim               5             1  2026-04-10
M005    swim                       8             2  2026-04-13
M097    gym and swim               7             2  2026-04-02
M085    swim                      10             5  2026-04-18
saved call_list.csv

Read one row to check that the output means what you think. Member M101 made five visits in the four weeks to 29 March, none since, and was last seen on 18 March. That is the kind of member the team lead described.

Send this list to the membership team lead on day 3 and ask one thing: does it look sensible? She knows things the data does not. If half the list turned out to be staff, or a swimming club that moved to another pool, you would want to know now and not during the demo.

Test the rule, and little else

A proof of concept does not need the tests a product needs. It needs the rule its numbers rest on to be right, because a mistake there makes every figure you report wrong.

Create test_score.py. Each test builds one made-up member and checks the rule.

import unittest
from datetime import date, timedelta

from score import call_list

AS_OF = date(2026, 3, 30)


def days_ago(*numbers):
    return [AS_OF - timedelta(days=number) for number in numbers]


def member(cancelled_on=None):
    return {"plan": "gym", "joined": None, "cancelled_on": cancelled_on}


class CallListTests(unittest.TestCase):
    def test_a_member_whose_visits_halved_is_listed(self):
        visits = {"A": days_ago(50, 45, 40, 35, 10, 5)}
        self.assertEqual([row["member_id"] for row in call_list({"A": member()}, visits, AS_OF)], ["A"])

    def test_a_steady_member_is_not_listed(self):
        visits = {"A": days_ago(50, 45, 40, 35, 20, 15, 10, 5)}
        self.assertEqual(call_list({"A": member()}, visits, AS_OF), [])

    def test_too_few_visits_to_judge_is_not_listed(self):
        visits = {"A": days_ago(50, 40, 35)}
        self.assertEqual(call_list({"A": member()}, visits, AS_OF), [])

    def test_a_member_who_already_cancelled_is_not_listed(self):
        visits = {"A": days_ago(50, 45, 40, 35)}
        self.assertEqual(call_list({"A": member(AS_OF - timedelta(days=3))}, visits, AS_OF), [])

    def test_visits_on_or_after_the_day_are_not_used(self):
        visits = {"A": days_ago(50, 45, 40, 35) + [AS_OF, AS_OF + timedelta(days=2), AS_OF + timedelta(days=4)]}
        rows = call_list({"A": member()}, visits, AS_OF)
        self.assertEqual((rows[0]["before"], rows[0]["recent"]), (4, 0))

    def test_the_biggest_fall_comes_first_and_the_list_is_cut_to_size(self):
        visits = {"A": days_ago(50, 45, 40, 35, 10, 5), "B": days_ago(50, 45, 40, 35), "C": days_ago(50, 45, 40, 35, 5)}
        members = {name: member() for name in visits}
        self.assertEqual([row["member_id"] for row in call_list(members, visits, AS_OF, size=2)], ["B", "C"])


if __name__ == "__main__":
    unittest.main()
python -m unittest

The output ends with a line saying that 6 tests ran, and then OK.

The fifth test is the one to notice. It gives a member visits on and after the day the list is made, and checks that they are ignored. Lesson 4 depends on exactly that.

What days 2 and 3 produced

You now have a list the customer could use on Monday. You do not yet know whether it is any good. A list of members who stopped coming looks convincing, and looking convincing is not the pass test. Day 4 finds out.

Key takeaways

  • Get something working from end to end first, then improve the weakest part.
  • Start with a rule a person can read and check; reach for something cleverer only if the simple rule fails the test.
  • Put the data decisions in one place, so that every later step reads the same cleaned data.
  • Hard-code what the question does not depend on.
  • Test the rule that the result rests on, including its edges, and little else.

Try it

Predict, then check, what happens at the edge of the rule. Add two tests to test_score.py: a member with four visits in the earlier period and exactly two in the recent one, and a member with four and then three. Before you run them, write down whether each member should be on the list. A good result has both tests passing: the first member is listed, because the rule is "half or less", and the second is not.

Official documentation

Ready to use this in a job?

Rolebound applies to matching roles for you.

Start now

Written with AI and checked automatically. Nobody has run these steps by hand, and tools change, so a command may behave differently in the version you install. Spotted a mistake? Tell us.

    Cookies on Rolebound

    We use necessary cookies to sign you in and keep the site working — those cannot be turned off. We would also like to set analytics and advertising cookies so we can see which pages help people get interviews and which adverts brought them here. Nothing optional is set unless you say yes, and you can change your mind at any time from “Cookie settings” in the footer. Read our Privacy Policy.