What is an idempotent operation?

前端 未结 15 915
情话喂你
情话喂你 2020-11-22 03:27

What is an idempotent operation?

15条回答
  •  忘了有多久
    2020-11-22 03:39

    Idempotence means that applying an operation once or applying it multiple times has the same effect.

    Examples:

    • Multiplication by zero. No matter how many times you do it, the result is still zero.
    • Setting a boolean flag. No matter how many times you do it, the flag stays set.
    • Deleting a row from a database with a given ID. If you try it again, the row is still gone.

    For pure functions (functions with no side effects) then idempotency implies that f(x) = f(f(x)) = f(f(f(x))) = f(f(f(f(x)))) = ...... for all values of x

    For functions with side effects, idempotency furthermore implies that no additional side effects will be caused after the first application. You can consider the state of the world to be an additional "hidden" parameter to the function if you like.

    Note that in a world where you have concurrent actions going on, you may find that operations you thought were idempotent cease to be so (for example, another thread could unset the value of the boolean flag in the example above). Basically whenever you have concurrency and mutable state, you need to think much more carefully about idempotency.

    Idempotency is often a useful property in building robust systems. For example, if there is a risk that you may receive a duplicate message from a third party, it is helpful to have the message handler act as an idempotent operation so that the message effect only happens once.

提交回复
热议问题