Card 06/ 09
All 9 cards
GotchaDifficulty: Intermediate1 min
Why Your Retry Policy Tried Four Times
The configuration says three retries. The support ticket has four attempts in the log, four charges on the card, and a customer who is unhappy about the fourth.
int maxRetries = 3;
int attempt = 0;
while (attempt <= maxRetries) {
send(payment);
attempt++;
}attempt starts at zero, so the body runs for 0, 1, 2 and 3 — four passes for a limit of three. <= on a counter that starts at zero always runs one more time than the number on the right.
| Condition | Highest value | Passes | Outcome |
|---|---|---|---|
attempt < maxRetries | 2 | 3 | Three attempts, as configured |
attempt <= maxRetries | 3 | 4 | One attempt too many |
attempt < maxRetries - 1 | 1 | 2 | One attempt too few, and nothing says so |
Start the counter at zero and compare with <, or start it at one and compare with <=. Mixing the two is where every loop that is one out comes from, and picking one convention and keeping it is cheaper than checking each loop.