An idempotent loop body stops changing the relevant state, so repeated iterations revisit the same condition and may never terminate. A missing state update can hide behind passing unit tests and complete code coverage. section 3.8
Unique identifiers
A unique-ID loop assigns the original ID, then tries suffixes such as _1 or _2. If the body omits i++, it repeatedly tests the same occupied suffix and loops forever. Adding i++ advances the search. Tests for an empty set and one existing ID pass, but a set containing both id and id_1 exposes the failure. section 3.8
static String makeUniqueId(String id, Set<String> usedIds) {
int i = 1;
String uniqueId = id;
while (usedIds.contains(uniqueId)) {
uniqueId = id + "_" + i;
}
return uniqueId;
}
Inspect the faulty unique-ID loop whose suffix counter never advances. section 3.8
Avoid and investigate the pattern by:
- Ensuring every iteration changes the state relevant to the loop condition. section 3.8
- Testing inputs that force repeated iterations rather than relying on coverage percentages. section 3.8
- Using IntelliJ IDEA's inspection for simple cases, while recognizing that interprocedural cases may escape detection. section 3.8
