Defining Idempotence

2020-02-28 03:57发布

问题:

So "idempotence" can be defined as:

An action, that if performed N times has the same effect as performing the action only once.

Got it, easy enough.

My question is about the subtlety of this definition -is an action considered idempotent by itself, or must you also consider the data being passed into the action?

Let me clarify with an example:

Suppose I have a PUT method that updates some resource, we'll call it f(x)

Obviously, f(3) is idempotent, as long as I supply 3 as the input. And equally obvious, f(5) will change the value of the resource (i.e., it will no longer be 3 or whatever value was there previously)

So when we talk about idempotence, are we referring to the generalization of the action/function like (i.e., f(x)), or are we referring to action/function + the data being passed into it (i.e., f(3))?

回答1:

Suppose I have a PUT method that updates some resource, we'll call it f(x)

Obviously, f(3) is idempotent, as long as I supply 3 as the input. And equally obvious, f(5) will change the value of the resource (i.e., it will no longer be 3 or whatever value was there previously).

This is only obvious is the server implementation is such that PUT respects this idempotent property. In the context of HTTP, RFC 2616 says:

Methods can also have the property of "idempotence" in that (aside from error or expiration issues) the side-effects of N > 0 identical requests is the same as for a single request.

Going a bit off topic... In a distributed system like the web, you may also want to consider commutativity and concurrent requests. For example N+1 of the same PUT(x1) request should have the same effect, but you don't know if another client made a different PUT(x2) request in between yours, so while nPUT(x1)=PUT(x1) and mPUT(x2)=PUT(x2), the two sets of requests could be interleaved.



回答2:

Idempotence requires that the action holds for all values over its domain, i.e., f(f(x)) = f(x) for all x. Another way to think about it is that an operation is idempotent if the composition of the operation with itself is just that operation.



回答3:

You're assuming idempotence means that the state of the server will be changed at most once by a series of invocations. Most of the time, people use this term to mean that the state on the server won't be changed at all by any number of invocations. Under these circumstances, the distinction between your two cases is immaterial.



回答4:

This is not quite the definition of idempotence. A function is idempotent if for any item x, f(f(x)) == f(x).

PUT is a side effect of your f() function here, not the result of it.