liveBook · Manning

Idempotency

As explained in 100 Java Mistakes and How to Avoid Them

An idempotent operation is an operation whose repeated application has the same resulting effect as applying it once, even though it may produce a side effect.

An idempotent operation may produce a side effect, but repeating it produces the same result as applying it once. Assignment such as x = 0 is idempotent; x += 10 is not because each execution depends on the previous value. section 3.8

An idempotent loop body can leave the loop condition unchanged. If the condition starts true, the loop then runs forever; if it never repeats, the loop may be redundant and better expressed as an if statement. section 3.8

A unique-ID loop that never advances

makeUniqueId checks whether uniqueId is already used, but its loop body never changes uniqueId. Calling makeUniqueId("id", Set.of("id", "id_1")) therefore repeats the same check indefinitely instead of trying another candidate.

Prevent idempotent-loop mistakes by checking:

  • Whether the body changes the state tested by the condition. section 3.8
  • Whether a for-loop update statement advances toward termination. section 3.8

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains repeated effects, loop outcomes, redundant-loop replacement, and a production-style infinite loop.
Examples
Uses assignments, arithmetic updates, a unique-ID generator, and string-scanning tests to expose repeated-state failures.
What you can do after
Diagnose infinite or redundant loops by checking whether each iteration changes the condition’s relevant state.
How it connects
Connects idempotency with side effects, loops, termination, conditional statements, and test cases.

Also explained in

Compare how 17 books explain idempotency →

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.