Practice question · Multiple choice
Extracting repeated code into a function usually makes a program longer, not shorter, once the definition and calls are counted. Why is that a good trade?
Hints
- Suppose you find a bug in that logic. How many places must you edit in each version?
- Ask what a well-named function call tells a reader that a block of inline code does not.
Show the answer
B. One place where the logic lives, so a fix is made once.
Why
Duplicated logic means duplicated bugs, and the failure mode is fixing four of five copies, worse than not noticing, because the bug now appears intermittently. The name does real work too: is_valid_email(s) tells a reader what the code accomplishes without their reading how. A call costs a little, so modularity is bought at a small runtime price worth paying.
Practise Functions and Modularity
The app has 6 more questions on this lesson, and keeps your place in the course. Mathematics I is free to start.
More questions on Functions and Modularity
- A function that reads no globals and changes nothing outside itself is called pure. Why do such functions…
- Sort each change to a function by whether existing callers keep working untouched.
- If two different functions each define a local variable named count, changing one of them changes the other.
- Order what happens when the call f(3, 4) is evaluated.