Boundaries: where off-by-one bugs live
An off-by-one error is a bug where code is wrong by exactly one unit, almost always at a boundary: the value where behavior is supposed to change. Free shipping at 50. Grade A at 90. Teen from 13 to 19. The classic cause is mixing up > and >=, or < and <=.
The hunting technique is called boundary value analysis and it is mechanical:
- find each boundary value in the spec
- test exactly at the boundary
- test one step below and one step above
Three cheap tests per boundary. A > where >= belongs passes the below and above tests but fails the at test, so this trio catches the entire bug family.
Code exercise · python
Run the boundary trio for free shipping at 50. All three pass because the code correctly uses >=.
Code exercise · python
Your turn. The spec says 90 and above is an A, but a student with exactly 90 got a B. The boundary tests below catch it: run, read the FAIL line, and fix the single wrong character in letter_grade.
Code exercise · python
Second hunt, no help this time. The spec: a teen is 13 to 19 inclusive. Someone who is exactly 13 is being told they are not a teen. Run the boundary tests, read the FAIL, and fix the single wrong character.
Quiz
A password is valid when its length is 8 to 20 inclusive. Which set of lengths is the best boundary-analysis test set?