Boss lesson · Unit 02
Break up a long function
Extract, inline and reorder without changing the bill
What you practise
- Extract variable, extract function, inline, move: each step small, each step run against the same checks, the order that keeps it working
Try a question from this lesson
Pick one
The comments mark three jobs. What do they suggest about how to split this function?
def bill(cart, code):
# subtotal
sub = 0
for price, qty in cart:
sub += price * qty
# discount
if code == "SAVE10":
sub -= sub // 10
# shipping
ship = 0 if sub >= 50 else 5
return sub + shipfunction bill(cart, code) {
// subtotal
let sub = 0;
for (const [price, qty] of cart) {
sub += price * qty;
}
// discount
if (code === "SAVE10") {
sub -= Math.floor(sub / 10);
}
// shipping
const ship = sub >= 50 ? 0 : 5;
return sub + ship;
}function bill(cart: Cart, code: string) {
// subtotal
let sub = 0;
for (const [price, qty] of cart) {
sub += price * qty;
}
// discount
if (code === "SAVE10") {
sub -= Math.floor(sub / 10);
}
// shipping
const ship = sub >= 50 ? 0 : 5;
return sub + ship;
}Correct answer
Each block can be a function named after its comment
Why
A comment that labels a block is a function name waiting to be used. Extract the block, give it that name, and the comment is no longer needed because the call says the same thing.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Extract function
Move a block into its own function. What the block reads becomes parameters; what it produces is returned.
The old spot shrinks to one call whose name says what the block did. Do one extraction, run your checks, and only then start the next.
def subtotal(cart):
total = 0
for price, qty in cart:
total += price * qty
return total
def bill(cart, code):
sub = subtotal(cart)
if code == "SAVE10":
sub -= sub // 10
ship = 0 if sub >= 50 else 5
return sub + shipfunction subtotal(cart) {
let total = 0;
for (const [price, qty] of cart) {
total += price * qty;
}
return total;
}
function bill(cart, code) {
let sub = subtotal(cart);
if (code === "SAVE10") {
sub -= Math.floor(sub / 10);
}
const ship = sub >= 50 ? 0 : 5;
return sub + ship;
}function subtotal(cart: Cart): number {
let total = 0;
for (const [price, qty] of cart) {
total += price * qty;
}
return total;
}
function bill(cart: Cart, code: string) {
let sub = subtotal(cart);
if (code === "SAVE10") {
sub -= Math.floor(sub / 10);
}
const ship = sub >= 50 ? 0 : 5;
return sub + ship;
}10 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 2× multiple choice
- 2× order the lines
- 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.