liveBook · Manning

Idempotent loop body

As explained in 100 Java Mistakes and How to Avoid Them

An idempotent loop body is a loop body whose repeated execution does not further change the relevant program state after an initial execution.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Demonstrates infinite-loop failures, inadequate coverage, missing increments, conditional idempotence, and static-analysis limits.
Examples
Uses makeUniqueId, suffix retries, escaped percent signs, assertions, JaCoCo, and Pitest.
What you can do after
Diagnose non-advancing loops with targeted inputs and static analysis, then repair them by advancing loop state.
How it connects
Connects loop termination with unit testing, code coverage, mutation coverage, static analysis, and interprocedural analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.