News for hackers. Stuff that matters.
Re:Heard of Idempotency but unsure what it is? by happytoexplain on Monday June 10, 2024 @06:06PM (#40639749)
The world is a system that has state. If two invocations of your function with the same parameters both mutate any part of that state, and nothing else mutated that part in between, then it's not idempotent. In this case, there are now two emails in the recipient's inbox.

I.e. "result" refers to state, not actions. "Send one email saying 'hi'" is an action. "There is one email saying 'hi' in their inbox" is a result.

There is also usually an implicit limiting scope (except in very pure functional contexts). E.g. just because two invocations both produce entries in an activity log somewhere doesn't usually count as "not idempotent".

You can also think of it in terms of declarative vs imperative. 'x = 1' is declarative (and idempotent). 'x += 1' is imperative. YMMV with this use of those terms, though.

To oversimplify, an idempotent function is "safe to spam", e.g. if you're not sure it worked the first time, you can do it again without worrying about duplication. A very relevant concept in networked communication.

Edit: I should also clarify that "same parameters" includes any state the function reads that is mutable over the scope in which you would like to define idempotency. I.e. if the function reads some external state that might change between calls, that counts as "parameters" in my simplified definition.

Re:Heard of Idempotency but unsure what it is? by PaulDavisThe1st on Monday June 10, 2024 @06:45PM (#40640124)
> If two invocations of your function with the same parameters both mutate any part of that state, and nothing else mutated that part in between, then it's not idempotent.

Still not accurate. What matters is whether N calls to the function changes the state differently than a single call. If not, then the function is idempotent.

Another issue with idempotency is that there's an implicit temporal component that is rarely explicitly discussed. Most people don't expect a function to necessarily be idempotent over long periods of time.

Re:Heard of Idempotency but unsure what it is? by happytoexplain on Monday June 10, 2024 @07:47PM (#40640652)
>What matters is whether N calls to the function changes the state differently than a single call.

I thought "any 2" would be the relevant subset of "N" that you can use to define idempotency in simpler terms. Also, I'm using the phrase "mutate state" as shorthand for your "change state differently", I think. I.e. if two things both change state, then by definition they changed it "differently". If two things both set x to 1, the second one didn't "change state".

>there's an implicit temporal component ... idempotent over long periods

This sounds a bit like what I mentioned about other things touching state between calls to your idempotent function.

Maybe I meant the same thing as you, but used different words?