cs-054 — Refactor the Monolith
| Field | Value |
|---|---|
| id | cs-054 |
| difficulty | Foundational |
| topics | functions, refactoring |
| lecture | lecture-14 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | lectures 1-2 (problem framing, precise pseudocode) |
| objective | recognise the pattern, translate it into precise steps, and trace it correctly |
| solution | held by the instructor; discussed after the attempt |
Problem
One 40-line script computes grade statistics. Decompose it into functions without changing behaviour, then defend the boundaries chosen.
Your deliverable is the function list with contracts, the composed driver, and one input per function that exercises its edge. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: one script: parse score lines, drop missing, average per student, print report
- Output: functions parse_line, averages, format_report - behaviour unchanged; test by identical output
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- Refactor in steps: extract, run, compare output. Never change two things at once.
- A good function name is a miniature specification.
- Return values compose; printed output does not.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Which cut line would you move, and what argument justifies the boundary?"
Constraints and assumptions
- Difficulty: Foundational (early-semester techniques assumed: precise statements, traces, simple loops).
- Topics: functions, refactoring.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes; naming the pattern and stating the assumption is already a pass, completing the calculation is the stretch.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Split one function into two and defend the new contract boundary.