109

(Assuming a single-threaded environment)

A function that fulfills this criterion is:

bool MyClass::is_initialized = false;

void MyClass::lazy_initialize()
{
    if (!is_initialized)
    {
        initialize(); //Should not be called multiple times
        is_initialized = true;
    }
}

In essence, I can call this function multiple times and not worry about it initializing MyClass multiple times

A function that does not fulfill this criterion might be:

Foo* MyClass::ptr = NULL;

void initialize()
{
    ptr = new Foo();
}

Calling initialize() multiple times will cause a memory leak

Motivation

It would be nice to have a single concise word to describe this behavior so that functions that are expected to meet this criterion can be duly commented (especially useful when describing interface functions that are expected to be overridden)

22
  • 69
    To the close voter(s): while it is true that 99.999% (rough estimate) of all "name-that-thing" questions are off-topic because they don't have a single, correct, unambiguous, objective answer and the naming is purely subjective and opinion-based, this one does have a single, correct, unambiguous, objective answer, which was given by the OP himself. Commented Mar 4, 2019 at 8:38
  • 31
    Calling it multiple times does have an effect, as there could be other code that changed 'var' in between. Commented Mar 4, 2019 at 9:50
  • 7
    Why was this question asked, if the OP knew the answer at the time of asking? Is there any reason other than rep/points/karma building?
    – dotancohen
    Commented Mar 4, 2019 at 16:29
  • 13
    @dotancohen Q/A style self-answering is one of the key concepts on StackExchange.
    – glglgl
    Commented Mar 4, 2019 at 16:31
  • 18
    @glglgl: I agree, for questions with merit. What merit has this question? I'm seriously concerned that we'll start getting every CS 101 question asked and immediately answered by the OP, every single CS term asked and immediately defined by the OP, and every basic algorithm's pros and cons questioned then immediately answered by the OP (not necessarily this OP). Is that the site that we want softwareengineering.SE to be?
    – dotancohen
    Commented Mar 4, 2019 at 16:37

6 Answers 6

255

This type of function / operation is called Idempotent

Idempotence (UK: /ˌɪdɛmˈpoʊtəns/,[1] US: /ˌaɪdəm-/)[2] is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

In mathematics, this means that if f is idempotent, f(f(x)) = f(x), which is the same as saying ff = f.

In computer science, this means that if f(x); is idempotent, f(x); is the same as f(x); f(x);.

Note: These meanings seem different, but under the denotational semantics of state, the word "idempotent" actually has the same exact meaning in both mathematics and computer science.

1
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – maple_shaft
    Commented Mar 7, 2019 at 15:23
50

The precise term for this (as Woofas mentions) is idempotence. I wanted to add that while you could call your func1 method idempotent, you could not call it a pure function. The properties of a pure function are two: it must be idempotent and it must not have side effects, which is to say, no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams.

The reason I mention this is that a idempotent function with side effects is not good either, since technically idempotent refers to the return output of the function, and not to the side effects. So technically your func2 method is idempotent, as the output doesn't change according to the input.

You most likely want to specify that you want a pure function. An example of a pure function might be as follows:

int func1(int var)
{
    return var + 1;
}

More reading can be found in the Wikipedia article "Pure function".

10
  • 37
    I think your definition of idempotency is too narrow, or put another way, you are using the mathematical definition of idempotency, not the programming one. For example, the PUT and DELETE HTTP methods are called idempotent precisely because executing their side-effects multiple times has the same effect as executing them only once. You are saying "idempotency means f∘f = f", whereas in programming, we mean "executing f has the same effect has executing f; f". Note that you can easily transform the second meaning into the former by adding a "world" parameter. Commented Mar 4, 2019 at 8:28
  • 23
    @Neil "Idempotency is strictly a mathematical term." No it isn't, its also used in networking and client server communication/distributed systems as well and is described as JörgWMittag describes it. Its a useful concept because it allows multiple requests to a server/client with the same operation/message with out changing what that original message set out to do. This is useful when you have unreliable communication, and you need to retry a command because either the clients message was dropped or the servers reply was.
    – Krupip
    Commented Mar 4, 2019 at 14:39
  • 8
    You should go into more detail about the difference between pure and idempotent. Your example func1 is not idempotent because func1(1) != func1(func1(1)).
    – Tezra
    Commented Mar 4, 2019 at 20:29
  • 5
    Purity and idempotence are different. A pure function doesn't have to be idempotent in mathematical sense (it is abviously idempotent in terms of side-effects, as it has none). Idempotent (in programming sense) function doesn't have to be pure, as in example given by OP. Also, as opa mentioned, idempotence is a useful property with a strictly different use than purity. Your definition of purity as "idempotent and with no side-effects" is wrong or at least misleading, downvoting.
    – Frax
    Commented Mar 4, 2019 at 22:55
  • 5
    In the context of programming, there are no "side effects", but if you were to expand the definition to include this, then a idempotent function and a pure function would mean the same thing. No, they wouldn't mean the same thing at all. Idempotent, not pure: void f(int var) { someGlobalVariable = var; }. Pure, not idempotent: int func1(int var) { return var + 1; }.
    – JLRishe
    Commented Mar 5, 2019 at 14:39
6

The Term is Idempotence. Note below that there is a distinct difference between an Idempotent function (Called recursively on itself; Second code block and the Mathematical definition), and functional idempotence (Called repeatedly with same input sequentially; First code block and often the term meant in Programming).

A function f with side effects is said to be idempotent under sequential composition f; f if, when called twice with the same list of arguments, the second call has no side effects and returns the same value as the first call[citation needed] (assuming no other procedures were called between the end of the first call and the start of the second call).

For instance, consider the following Python code:

x = 0

def setx(n):
    global x
    x = n

setx(5)
setx(5)

Here, setx is idempotent because the second call to setx (with the same argument) does not change the visible program state: x was already set to 5 in the first call, and is again set to 5 in the second call, thus keeping the same value. Note that this is distinct from idempotence under function composition f ∘ f. For example, the absolute value is idempotent under function composition:

def abs(n):
    if n < 0:
        return -n
    else:
        return n

abs(-5) == abs(abs(-5)) == abs(5) == 5
4

In addition to the other answers, if there is a specific input to the functon that has this property, it is a fixed point, invariant point or fixpoint of the function. For example, 1 to any power is equal to 1, so (1ⁿ)ⁿ = 1ⁿ = 1.

The special case of a program that produces itself as output is a quine.

1
  • Quines are to software as Cantor sets are to math :-) . And of course quines are not idempotent -- they either fail when the output already exists or they "clobber" the previous result and write a new, albeit identical output. Commented Mar 6, 2019 at 15:17
3

In physics I've heard this referred to as a projection:

a projection is a linear transformation P from a vector space to itself such that P2 = P. That is, whenever P is applied twice to any value, it gives the same result as if it were applied once (idempotent).

Graphically, this makes sense if you look at a cartoon of a vector projection:

enter image description here

In the picture, a1 is the projection of a on to b, which is like the first application of your function. Subsequent projections of a1 on to b give the same result a1. In other words, when you call a projection repeatedly, it has the same effect as calling it once.

Fair warning: I've never heard this used outside of physics, so unless you've got of those types on your team you might confuse everyone.

2
  • 3
    This is indeed a nice concrete example of how an idempotent function can be visualized (mathematically, and especially in the vector geometry / linear algebra field). While software function's "idempotence" is a really close concept, I don't think developers / computer scientist often use the word "projection" in this context (a "projection function" in software engineering would rather refer to a function that take an object and returns a new object derived from it, or a property of that object, for instance)
    – Pac0
    Commented Mar 4, 2019 at 22:47
  • 2
    @Pac0 Oh, ok. I work on the fringe between science and programming, and didn't realize the word was already overloaded. I can think of a few contrived examples at work where I would use this terminology, but I admittedly work with people that are willing to put up with science jargon on the daily :-) Commented Mar 5, 2019 at 1:21
3

It is a Deterministic algorithm because given the same input (in this case no input), it will always produce the same output.

In computer science, a deterministic algorithm is an algorithm which, given a particular input, will always produce the same output, with the underlying machine always passing through the same sequence of states. Deterministic algorithms are by far the most studied and familiar kind of algorithm, as well as one of the most practical, since they can be run on real machines efficiently.

SQL databases are interested in Deterministic functions.

A deterministic function always gives the same answer when it has the same inputs. Most built-in SQL functions in SQLite are deterministic. For example, the abs(X) function always returns the same answer as long as its input X is the same.

A function must be deterministic if it's used in calculating an index.

For instance, in SQLite, the following non-deterministic functions cannot be used in an index: random(), changes(), last_insert_rowid() and sqlite3_version().

3
  • 6
    The asker's func2 is deterministic (there are no random effects involved), but already declared as violating the property he is looking for. Commented Mar 4, 2019 at 22:17
  • That the same result is produced by repetition is not the same as saying the same result is produced by nesting or chaining. Deterministic functions are important for caching results, more so than for indexing/hashing.
    – mckenzm
    Commented Mar 5, 2019 at 5:59
  • While OP's function might be deterministic, "deterministic" is not the name for a function that produces no further changes after its first invocation. For example, print("hello world") is deterministic but not idempotent. Commented Dec 2, 2023 at 0:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.