Section 6.9 Eliminating Repetitive Code
The key to eliminating the duplicate code is to take the calculation of the total price and make it a function with two parameters: the unit price and the quantity purchased. This function will return the total price. We can then call this function twice: once with the information for the first purchase, and again with the information for the second purchase.
Here are some important things to note:
- The names of the parameters (
price
andquantity
) do not have to be the same as the names of the arguments. - Arguments are copied into the parameters in the order they appear. In the call
calculate_total(price1, qty1)
, the value of argumentprice1
is copied into parameterprice
, and the value of argumentqty1
is copied into paramterquantity
. - The function definition (starting in line 1) must appear before the function is called (in lines 18 and 19). We’ll examine this in a bit more detail on the next page.