๐ WAYPOINT LESSON
Writing code from prose
โญ beginnerโณ 12 min read๐ Lesson 70 of 256
Restate, choose the traversal, skeleton first, exploit preconditions.
Writing code from prose โ the specification is a paragraph, the answer is a method. The workflow:
- Restate the postcondition as a formula or loop invariant.
- Choose the traversal (array? string? list? which direction?).
- Write the accumulator skeleton FIRST, fill the body SECOND.
- Check the preconditions for shortcuts you may take.
Example spec: "Return the number of times the character ch appears in the string s, ignoring case." Restated: loop over every index of s, compare case-folded characters to ch, count matches.
public static int countIgnoreCase(String s, char ch) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (Character.toLowerCase(s.charAt(i)) == Character.toLowerCase(ch)) {
count++;
}
}
return count;
}
Common spec-reading failures, in order of frequency:
- missing the "ignoring case" / "ignoring order" / "at most" qualifier;
- returning the wrong shape (index vs value, count vs list);
- handling the empty input wrong (or crashing on it);
- shadowing the parameter (
String sthenint s = 0).