Decomposition and the Edge-Case Habit
beginner11 min readLesson 61 of 204
The five-step method, writing edge cases BEFORE the solution, and the discipline that turns hard problems into easy ones.
The five-step method
- Restate the problem in your own words, one sentence. If you cannot, you are not ready to code.
- Work an example by hand โ input, steps, output. The by-hand trace IS the algorithm sketch.
- Find the edges first: empty input, one element, duplicates, extremes, zero/negative. Write them as test cases before coding.
- Decompose: name the stages (parse โ compute โ format) โ each becomes a function.
- Implement the happy path, then the edges. Compile often.
Why edges first
Edge cases discovered after coding force redesign; discovered before coding, they only constrain it. "What if the list is empty?" changes your function's shape (early return? sentinel?) โ asking late costs a rewrite, asking early costs a minute.
Worked micro-example
"Return the second-largest value in a vector."
- Restate: largest, then the largest among the rest.
- By hand:
{4, 9, 2, 9}โ remove one 9 โ second largest is 9 again (duplicates count!).{5}โ none. - Edges: empty โ throw or 0? Decide and document. One element โ none. Duplicates of the max โ still valid second-largest.
- Decompose:
int second_largest(const std::vector<int>&)โ one pass tracking two values.
The exercise set practices exactly this loop on progressively harder problems.