Section 6.8 Repetitive Code
Here is a program that helps users do comparison shopping. It asks them to enter the price per unit and quantity of two different purchases. It calculates the total cost for each purchase and prints them out so that the user can see which one is the better deal.
The store gives a discount based on the quantity purchased: if you buy 20 or more of an item, you get 10% discount. If you buy 10–19 of an item, you get a 7% discount, and you get no discount for purchasing a quantity less than 10.
First, I have to emphasize: there’s nothing wrong with this program. It works exactly as advertised. It just has a lot of duplicated code. What if we decided to change the 7% discount to a 5% discount? We’d have to make sure we changed the discount on both lines 11 and 19. And imagine what the code would look like if we had three purchases, or if there were four different levels of discount based on quantity. The code would rapidly become unmanageable.
On the next page, we’ll use a function to eliminate some of that duplicated code.