Programming a PB&J
The above post reminded me of an analogy I once heard to try to explain to non-programmers what programming is actually like.
Suppose you are teaching someone how to make a peanut butter and jelly sandwich. For most people, the instructions would look something like:
- Get two slices of bread
- Put peanut butter on one and jelly on the other
- Put the two slices together
This would not work for a computer, though. If we look closer at just that first step, we would need to tell the computer to get the slices of bread from the pantry.
Error: could not find slices of bread. Found: loaf of bread, jar of peanut butter, [...]
There was a logical skip in our instructions: to get the loaf out and take slices from it. The computer doesn't know how to infer that step (ignoring machine learning/artificial intelligence), so it fails.
If we extrapolate this further and remove any assumptions about how to make a sandwich and what to do if the current state is not as we expect (e.g. a door is closed but instructions assume it is open), we get the following list of computer-friendly instructions:
- If the pantry door is shut, open the pantry door.
- Take the loaf of bread and the jar of peanut butter and place them on the (assumed empty) counter.
- Open the bag containing the loaf of bread.
- If there are less than two slices remaining, abort.
- Take two slices from the loaf and place them on the (assumed clean) counter.
- Close the bag containing the bread.
- Open the jar of peanut butter.
- Open the silverware drawer.
- Take a knife from the silverware drawer.
- Use the knife to remove (a specific measurement) of peanut butter from the jar.
- Spread the peanut butter on the first slice of bread using the knife.
- Close the peanut butter jar.
- Place the bread and peanut butter back in the pantry.
- Close the pantry door.
- (Repeat peanut butter steps but with the jelly from the fridge.)
- Press the peanut butter side of the first slice against the jelly side of the second slice.
- Sandwich has been made.
Replies
My English teacher once taught this lesson, although I can't remember why (grammar rules?). I felt pretty clever with my list of ~20 steps until she pointed out, rather dramatically, that I hadn't described _how_ to get bread out of the bag by wrenching it apart and scattering slices across the front row of students.
To illustrate how "difficult" it is to program (finnicky may be a better word, if my understanding of English is correct), I will add some steps:
- First, loop through all rooms, if name === "pantry", then proceed with opening its door.
- You need to account for all possible errors, if there's no knives on the drawer, then run getKnife(), which in turn may need to run cleanKnife().
- You didn't close the drawer, you may hurt yourself bumping into it.
- After returning the peanut butter and jelly, you didn't go back to the counter.
This is just for fun, not to actually "correct" you :)
Source