EDDYMENS

Eddymens (List page)

Last updated 2023-09-15 05:18:42

What Is Idempotent In Programming?

Table of contents

Definition

The meaning of Idempotent in English (As something that remains unchanged) is about the same as that used in programming. There are different circumstances where we can describe a program or action as idempotent.

Examples

01: function adder(a, b) { 02: return a + b 03: } 04: 05: adder(1, 2) // 3 06: adder(1, 2) // 3 07: adder(1, 2) // 3 08: adder(1, 2) // 3 09: adder(1, 2) // 3

No matter how many times we run the function above the results will always be the same.

01: result = 0 02: 03: function adder(a, b) { 04: result += a + b 05: return result 06: } 07: 08: adder(1, 2) // 3 09: adder(1, 2) // 6 10: adder(1, 2) // 9 11: adder(1, 2) // 12 12: adder(1, 2) // 15

When we modify this code a bit by introducing the result variable to add up the results as we run the function several times, you notice we end up with different results. This makes the function non-idempotent.

Summary

When working with RESTful APIs, you will hear people say GET endpoints [→] should be idempotent. This is because calls made to a GET endpoint should typically return data and not modify it. However, POST endpoints are non-idempotent as they can be used to make database entries.

Here is another article you might like 😊 "What Is Dependence Injection?"