Lesson 2 · Unit 01
Functions
One job, few arguments, no surprises
What you practise
- One job at one level of detail, few arguments, flag arguments that hide two functions, guard clauses and early returns, hidden side effects
Try a question from this lesson
Pick one
A web handler needs the total of some orders, with nothing printed. Can it reuse this function as it is?
def report(orders):
total = 0
for price, qty in orders:
total += price * qty
print("Total:", total)
return totalfunction report(orders) {
let total = 0;
for (const [price, qty] of orders) {
total += price * qty;
}
console.log("Total:", total);
return total;
}function report(orders: Order[]) {
let total = 0;
for (const [price, qty] of orders) {
total += price * qty;
}
console.log("Total:", total);
return total;
}Correct answer
No: it also prints, so the two jobs are tied
Why
It returns the right number, but every call also writes a line of output. The function does two jobs, so nobody can have one without the other. Split it: one function returns the total, another prints it.
TypeScript noteOrder is declared elsewhere as the tuple type [number, number]: a price and a quantity. const [price, qty] unpacks one tuple, like price, qty = order in Python.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
One job
A function should do one thing. A quick test: describe it in one sentence. If you need the word "and", it is doing two.
Keep working something out apart from showing or saving it. The part that computes can then be reused and checked anywhere, and the part that prints stays tiny.
def order_total(orders):
total = 0
for price, qty in orders:
total += price * qty
return total
def report(orders):
print("Total:", order_total(orders))function orderTotal(orders) {
let total = 0;
for (const [price, qty] of orders) {
total += price * qty;
}
return total;
}
function report(orders) {
const total = orderTotal(orders);
console.log("Total:", total);
}function orderTotal(orders: Order[]) {
let total = 0;
for (const [price, qty] of orders) {
total += price * qty;
}
return total;
}
function report(orders: Order[]): void {
const total = orderTotal(orders);
console.log("Total:", total);
}TypeScript note: void says the function returns nothing useful. orderTotal has no return annotation: TypeScript infers number from the return total line.
9 more exercises in the app
- 3× type the answer
- 1× order the lines
- 2× multiple choice
- 1× true or false
- 1× fill the blanks
- 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.