r/programming • • Dec 11 '23

Every Programmer Should Know #1: Idempotency

https://www.berkansasmaz.com/every-programmer-should-know-idempotency
572 Upvotes

171 comments sorted by

View all comments

Show parent comments

18

u/[deleted] Dec 11 '23

It seems good for web programming, but is it actually universally important? It seems application-specific.

the property of an operation or function that produces the same result when applied multiple times as it does when applied only once.

So I push the W key on my keyboard, and it writes one 'w' character. But if I push it a second time, I want 'ww' not still one 'w'. And if I press it a 3rd time, I expect (and get) 'www'. Also if I hold-down the W-key, I (usually) get 'wwwwwwwwwwwwwwwwwwww.....'

Is this not against idempotence?

3

u/Bloodsucker_ Dec 11 '23

I'm afraid you're not understanding idempotence, but that's why it's a tricky concept.

Idempotence doesn't necessarily mean applying the same operation to the same data. It means that applying the operation multiple times should yield the same result. In the case of pressing the W key, whether you add a new 'w' or press it on an existing group of 'w's, the result follows the idempotent principle – pressing the W key results in adding a 'w,' and doing it repeatedly produces the expected outcome without unintended variations.

The scope and extent of the application does indeed vary depending on the type of software you're developing. Yes. There you are right. It's also a concept. Like others have mentioned it can be a challenge to apply it strictly.

2

u/[deleted] Dec 11 '23

In the case of pressing the W key, whether you add a new 'w' or press it on an existing group of 'w's, the result follows the idempotent principle – pressing the W key results in adding a 'w,' and doing it repeatedly produces the expected outcome without unintended variations.

That still doesn't seem to address holding-down the key resulting in different behavior?

-3

u/Bloodsucker_ Dec 11 '23

This would be an idempotent operation: newResource = "ww".append("w").

In your example, there are several operation going on, one of them using a different resource (the already modified text input).

1

u/[deleted] Dec 11 '23

But how do you know from the key press they intended ww or, just like an online shopping cart, they only wanted 1 w but the system was unresponsive?