So far, most of your functions have done one small job each, with a few calls at the bottom. In the last lesson, you also saw why a value that’s needed outside a function has to leave through return. Both ideas come together when a task is too big for one function.
In this lesson, you’ll take a small brief, plan it as a few functions on paper, wire them together before they work, and then fill in and check each one on its own. Breaking a program into small functions like this is called decomposition. Keep working in your scratch/ folder, because you’ll build one file step by step.
Start With a Plan in Comments
A bike rental stand by the lake wants a quick way to price a ride. Here’s its brief:
- A ride costs 2.50 dollars per hour.
- Rides of 3 hours or more get 2 dollars off.
- On weekends, the stand adds a surcharge of half the fee.
- The stand wants a line like
Total: 12.00 dollars.
One long function that calculates and logs the total would run, but you couldn’t check the discount without also checking the weekend rule, or reuse any part of it.
Instead, plan first. Write each job the brief describes as a comment:
// Work out the fee for a number of hours, with the discount
// Work out the weekend surcharge for a fee
// Add them up for the final price
// Show the total
For each comment, ask yourself: “Could I check this step on its own?” Each of the first three jobs takes some values and produces a number you could work out by hand, so each becomes a function. The last job only shows a result, so it stays outside any function, at the bottom of the file.
Next, give each function a descriptive name and decide what it takes and what it returns. That one-line description is the function’s contract, and it’s the comment you already write above a function:
rentalFee(hours)takes a number of hours and returns the fee in dollars.weekendSurcharge(fee)takes a fee and returns the surcharge in dollars.totalPrice(hours, isWeekend)takes the hours and whether it’s a weekend and returns the full price.
Notice that totalPrice() doesn’t redo the other two jobs. It will call rentalFee() and weekendSurcharge() and combine their answers.