Boss lesson · Unit 01
Make it readable
One tangled function, cleaned up without changing a result
What you practise
- Comments that say why, not what
- Magic numbers into named constants
- Dead code removed
- One tangled function rewritten step by step with the same output
Try a question from this lesson
Pick one
Which number in this function should NOT be pulled out into a named constant?
def calc(l):
t = 0
for x in l:
# check if late
if x > 14:
t = t + (x - 14) * 25
# cap
if t > 1000:
t = 1000
return tfunction calc(l) {
let t = 0;
for (const x of l) {
// check if late
if (x > 14) {
t = t + (x - 14) * 25;
}
}
// cap
if (t > 1000) t = 1000;
return t;
}function calc(l: number[]): number {
let t = 0;
for (const x of l) {
// check if late
if (x > 14) {
t = t + (x - 14) * 25;
}
}
// cap
if (t > 1000) t = 1000;
return t;
}Correct answer
The 0 that starts the sum
Why
14, 25 and 1000 are library policy: each one means something and may change. A sum starting at 0 is just how adding works, and a name like ZERO would say nothing new. Name the numbers that carry a decision.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Comments say why
Code already says what happens. A comment that repeats it, like "check if late", is noise, and it goes stale when the code changes.
Keep comments for what code cannot say: the reason. Why 14 days, why a cap. When a comment explains what a block does, a better name can usually replace it.
# Capped: a lost book never costs
# more than buying a new copy.
MAX_FEE = 1000// Capped: a lost book never costs
// more than buying a new copy.
const MAX_FEE = 1000;// Capped: a lost book never costs
// more than buying a new copy.
const MAX_FEE = 1000;10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 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.