Lesson 1 · Unit 04
A safety net
Record what the code does today, then move in small steps
What you practise
- Tests that pin down what the code does today, small steps, refactor and feature in separate commits, refactor against rewrite
Try a question from this lesson
Pick one
Before reshaping this function you record what it does today. For "a b", with two spaces, it returns "a--b", which looks wrong. What should the record say?
def slug(title):
lowered = title.lower()
return lowered.replace(" ", "-")function slug(title) {
const lowered = title.toLowerCase();
return lowered.replaceAll(" ", "-");
}function slug(title: string): string {
const lowered = title.toLowerCase();
return lowered.replaceAll(" ", "-");
}Correct answer
"a--b": what it returns today
Why
The record exists to tell you whether your reshaping changed anything, so it must hold what the code does now, pretty or not. Some caller may rely on the double dash. Whether it is a bug is a separate question for a separate change.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Pin it down first
Before changing the shape of code, write down what it does now: a few inputs, each with the output it gives today. These are your pins.
Run them after every step. If one fails, that step changed behaviour: undo it. The pins need not be clever. They need to exist and to run in a second.
PINS = [
("Hi There", "hi-there"),
("a b", "a--b"),
]
failed = 0
for title, want in PINS:
if slug(title) != want:
failed += 1const PINS = [
["Hi There", "hi-there"],
["a b", "a--b"],
];
let failed = 0;
for (const [title, want] of PINS) {
if (slug(title) !== want) failed += 1;
}const PINS: [string, string][] = [
["Hi There", "hi-there"],
["a b", "a--b"],
];
let failed = 0;
for (const [title, want] of PINS) {
if (slug(title) !== want) failed += 1;
}TypeScript note[string, string][] is a list of pairs: an input and the output recorded for it. The loop unpacks each pair into two names.
9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.