Practice question · Put in order
Order the steps of factoring duplicated logic into one reusable unit.
- Replace each copy with a call to that function
- Write one function whose parameters cover those differences
- Change the rule once, in the single remaining definition
- Compare the copies and identify what actually differs between them
- Notice that the same logic appears in several places
Hints
- You cannot design the parameters until you know what varies between the copies.
- The payoff step is last, and it is the reason the earlier steps were worth doing.
Show the answer
- Notice that the same logic appears in several places
- Compare the copies and identify what actually differs between them
- Write one function whose parameters cover those differences
- Replace each copy with a call to that function
- Change the rule once, in the single remaining definition
Why
The differences between copies determine the parameters, so they must be found before the shared function can be written; the call sites are then replaced, and only after that does a change become a one-place edit. Jumping straight to writing the function is how people produce a shared routine that does not actually fit every call site.
Practise Modular Decomposition and Reuse
The app has 6 more questions on this lesson, and keeps your place in the course. Computer Science I is free to start.
More questions on Modular Decomposition and Reuse
- Two modules each work perfectly and fail when combined. What kind of defect does that suggest, and why do…
- Match each modular-design term to what it describes.
- SavingsAccount extends Account and overrides applyMonthly(). A variable declared as Account is holding a…
- A date-handling module is being designed. Sort each item by whether it should be public or private.
- The same block of validation logic has been copy-pasted into six files. Select every consequence the lesson…