Exercise: Green Before, Green After

Take your first ticket from Sunrise Bakery: a receipt printer that needs the subtotal and tax on their own, and delivery from Monday. Change the working checkout code in small, safe steps (rename, pull a method out, add the rule), running the tests after every one.

Novice · C# · Java · Python · JavaScript · TypeScript · Updated

By

Every exercise in this course hands you code that works, and asks you to change it. That sounds harmless, and it's where most real bugs come from: someone changes working code and, without noticing, changes what it does. This first exercise is small on purpose. It teaches the one way of working that every later exercise uses, so that by the time the patterns arrive, changing code safely is a habit.

Before you start

You need one language set up, as in Setup: VS Code and Your Language, and to know how to run the tests, as in Running the Exercise Tests. The exercise is written in all five of the course's languages; pick the one you use.

Get the exercise code

Open this lesson's GitHub repository, github.com/ask-codey/exercise-dp-green-before-green-after, also linked from the Exercise box beside the lesson. Clone it into your course folder. In a terminal, in that folder:

git clone https://github.com/ask-codey/exercise-dp-green-before-green-after.git

Git makes a folder, exercise-dp-green-before-green-after, with the exercise code inside. If you can't clone it, click Code on the repository's page, then Download ZIP, and unzip it into your course folder instead.

The repository has a folder for each language: csharp, java, python, javascript and typescript. Each folder holds:

  • the bakery's checkout code, as it is today (the repository's README.md names the file for each language);
  • the tests, which you don't need to change;
  • a demo program that prints a morning at the counter.

In VS Code, choose File > Open Folder and open your language's folder, not the whole repository.

The ticket

From: the owner, Sunrise Bakery

  1. The new receipt printer prints three lines for every order: the subtotal (the products before tax), the tax, and the total. Its code is already written, and it calls subtotal(items) and tax(amount). They have to give exactly the numbers checkout uses, so the receipt always adds up.
  2. We start delivering on Monday. Delivery costs $5, and it's free for orders of $40 or more before tax. The delivery screen calls deliveredTotal(items) for what the customer pays: the products, the tax and the delivery.

Everything that works today has to keep working: the counter's totals mustn't change by a cent.

The checkout code works. It's also hard to read: one function does everything, with names like t and x. The three functions the ticket names are already there, because the other screens call them, but they don't do their jobs yet.

Green before, green after

Changing the shape of code without changing what it does is called refactoring. Renaming a variable is a refactoring. So is cutting a few lines out into a method of their own and calling it. What the code does stays exactly the same; only how it reads changes.

The tests are what make that safe. Think of them as a safety net under a trapeze: you can try a move because, if you slip, something catches you. Here, the four tests that pass at the start are the net. They're marked Keep this working. If one of them goes red after a change, that change altered what the bakery's code does, and you know at once, while it's one small step to undo.

So the workflow, in every exercise from now on, is:

  1. Green before. Run the tests before you touch anything, and see which pass.
  2. One small step. Make one change: a rename, one method pulled out, one new rule.
  3. Run the tests. Every Keep this working test should still be green.
  4. Repeat until the Not yet tests, the ticket's, are green too. That's green after.

Small steps feel slow. They're the fastest way there is, because you never have to hunt for which of twenty changes broke something.

What to do

  1. Run the tests. Four pass: what the bakery does today. Four fail: the ticket.
  2. Rename. Give t, x and i names that say what they hold, such as subtotal, tax and item. Run the tests: still four green.
  3. Pull a method out. Move the lines that add up the products into subtotal, and make the counter's total call it. Run the tests. Then the same for the tax line and tax. Run them again: the receipt's tests turn green.
  4. Add the rule. Write deliveredTotal from the pieces you now have, with the delivery fee's rule. Run the tests.
  5. Stop when all eight are green and the demo prints what When you're done shows.

If a Keep this working test goes red, undo your last step and take a smaller one. That isn't a failure: it's the net doing its job.

Check your work

Each language has its own command, run in the terminal in your language's folder (Terminal > New Terminal in VS Code). The repository's README.md has the full list, including the one-time setup for Python (a virtual environment and pytest) and TypeScript (npm install).

Language Run the tests Run the demo
C# dotnet test dotnet run --project BakeryCheckout
Java ./mvnw test (.\mvnw test in PowerShell) java src/main/java/Demo.java
Python python -m pytest python demo.py
JavaScript npm test node demo.js
TypeScript npm test node demo.ts

A failing test's message starts with Not yet: for the ticket's work, or Keep this working: if a change broke something that worked, and says what it expected, for example Not yet: a $20 order is under $40, so delivery costs $5: $20 plus $1 tax plus $5, $26.

Hints

  • Don't write the tax math a second time. It's already in the counter's total. If there are two copies, they can drift apart, and the receipt stops adding up.
  • Tax is rounded down to whole dollars, the same way the counter does it now: // in Python, Math.floor in JavaScript and TypeScript, and whole-number division in C# and Java.
  • "$40 or more" includes $40. One of the tests checks exactly that.

When you're done

All 8 tests are green, and the demo prints the same five lines in every language:

Subtotal: $50
Tax: $4
Total at the counter: $54
Delivered: $54
Small order, delivered: $26

The counter's total is still $54, exactly as before: the four Keep this working tests prove it. That's the whole point of the workflow.

Submit your exercise

The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here.

  1. On GitHub, click +, then New repository. Name it (for example exercise-dp-green-before-green-after), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. In a terminal in your exercise folder (Git Bash on Windows), send your work to your new repo. If you cloned the starter, point your copy at your own repo, then commit and push:

    git remote set-url origin https://github.com/your-name/exercise-dp-green-before-green-after.git
    git add .
    git commit -m "My solution"
    git push -u origin main
    

    If you downloaded the ZIP instead:

    git init -b main
    git add .
    git commit -m "My solution"
    git remote add origin https://github.com/your-name/exercise-dp-green-before-green-after.git
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-dp-green-before-green-after, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.

Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.

So what

Green before, small steps, green after: that's how working developers change code they can't afford to break, and it's how you'll reshape every app in this course. Next, the object-oriented code every pattern is made of.

Key terms

Related