Sobes.tech
Junior — Middle

Can you explain what is meant by the property of idempotency in programming?

sobes.tech AI

Answer from AI

Idempotence in programming is a property of an operation whereby multiple executions of the same operation with the same input data do not change the system's state after the first call.

In simpler terms, if you call a function multiple times with the same parameters, the result and state will remain the same as after the first call.

Example:

  • The HTTP GET method is idempotent — a request to retrieve data can be repeated without changing the server's state.
  • The HTTP PUT method is usually idempotent — updating a resource with the same data does not change the result upon repeated calls.

In code, this means that a function should not have side effects, or these effects should be the same upon repeated calls.

public class Counter {
    private int value = 0;

    // Non-idempotent method
    public void increment() {
        value++;
    }

    // Idempotent method
    public void setValue(int newValue) {
        value = newValue;
    }
}

Here, increment() changes the state with each call, while setValue(5) always sets the same value regardless of how many times it is called.