A sandwich wouldn’t be complete without fries and dessert!
Here are the instructions to make the complete meal:
Oof. All of the instructions are there, but they’re confusing and hard to edit. If you decide to ask for a fruit salad instead of fries, you would have to find all of the fries-related instructions and replace every line.
To make it easier to read, we’ll separate and organize our instructions:
Add bread, Add burger patty, Add pickles, Add bread
Add fried potatoes, Add salt, Add ketchup
Add chocolate scoop, Add vanilla scoop, Add strawberry scoop
Better… Now let’s group these instructions into three functions:
We can easily substitute one line,
makeSomeFries(), for a different function, like
makeFruitSalad(). And if there’s an error, we know where to look for the recipe for each part of the meal.
The new instructions are starting to look like a program! By using functions, we made it easier to read, reusable, and modular: each set of related instructions (sandwich, fries, dessert) is grouped into its own function, which we can easily add, remove, and swap to make a diversity of meals.
“I’d like a sandwich, fries, and triple ice cream scoop, please!”
Questions: Which approach was easier? Which approach was less prone to error?
“I’d like 3 sandwiches, 2 fries, and 2 triple ice cream scoop, please!”
Question: Which approach was easier this time?