106

(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)

Rufus
  • 1,437
  • 3
  • 9
  • 11
  • 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. – Jörg W Mittag Mar 04 '19 at 08:38
  • 31
    Calling it multiple times _does_ have an effect, as there could be other code that changed 'var' in between. – RemcoGerlich Mar 04 '19 at 09:50
  • 2
    also see https://stackoverflow.com/questions/4801282/are-idempotent-functions-the-same-as-pure-functions – nha Mar 04 '19 at 14:58
  • 1
    How can a function with no arguments be idempotent? – Walter Mitty Mar 04 '19 at 15:33
  • 4
    @WalterMitty: The same way a function with arguments is idempotent; it produces the same result, given the same input (which, in this case, is no input). I do hear what you are saying, though; it's clearly less useful with parameterless functions, but the examples do clearly illustrate the concept. – Robert Harvey Mar 04 '19 at 15:34
  • 1
    @WalterMitty Init() functions can easily have no arguments, and if well designed are idempotent. – Taemyr Mar 04 '19 at 16:11
  • 1
    @RobertHarvey By that argument, `func2` would be idempotent as well - it takes no input and produces the same `void` output no matter how often it is called. No, that's not helpful. In imperative programs, we need to consider the environment state (that the function is closing over and which it might mutate) as in- and output (in addition to arguments and return values) – Bergi Mar 04 '19 at 16:11
  • 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 Mar 04 '19 at 16:29
  • 13
    @dotancohen Q/A style self-answering is one of the key concepts on StackExchange. – glglgl Mar 04 '19 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 Mar 04 '19 at 16:37
  • 5
    @dotancohen That's a question to post, a topic to discuss, on Meta. – ChrisW Mar 04 '19 at 16:47
  • 1
    What does f(f(x)) mean if f takes no arguments. – Walter Mitty Mar 04 '19 at 17:09
  • 1
    @Bergi: You have to consider side-effects as well. – Robert Harvey Mar 04 '19 at 17:25
  • 7
    @dotancohen: To be honest, the top-voted answer doesn't have much merit. It would be better if the answer included examples illustrating why idempotence is important. This isn't Jeopardy. – Robert Harvey Mar 04 '19 at 17:28
  • 1
    @JörgWMittag: Whether a question is off-topic or not doesn't depend on the answer – BlueRaja - Danny Pflughoeft Mar 04 '19 at 20:14
  • 1
    Calling multiple times is the same effect as calling once? Comcast Technical Support - as a bonus, it's the same effect as not calling at all. – corsiKa Mar 04 '19 at 23:11
  • 3
    @dotancohen This has been a term that I repeatedly forget and found somewhat difficult to google (googling the title of this question doesn't turn up the desired result). Hence I made use of the "Answer your own question" function to provide some sort of "note to future self" in case I find the need to use this term again. Just thought I'd share it – Rufus Mar 05 '19 at 01:39
  • 4
    @dotancohen You aren't the authority on whether a Q/A has merit, the community is. the community has (so far) decided that the Q/A has merit. If you feel differently, cast your downvote and/or complain on Meta. Based on the upvotes this Q/A has, the community will disagree with you on Meta. – Greg Schmit Mar 05 '19 at 01:47
  • 1
    @dotancohen yes, that's the entire point of StackExchange. Who happens to get meaningless points and badges along the way is irrelevant. – OrangeDog Mar 05 '19 at 10:25
  • @BlueRaja-DannyPflughoeft: Actually, for "name-that-thing"-questions it does, because those questions are off-topic for being opinion-based if there is no answer (everybody has their own opinion what the name should be), off-topic for being a list question (too broad) if there are multiple answers, and *on-topic* IFF there is a single, canonical, correct, objective, agreed-upon term. That makes these questions very hard on the asker because in order to know whether the question is on-topic, you already need to know (the existence of) the answer. This was discussed on [meta] a couple of times. – Jörg W Mittag Mar 05 '19 at 22:10
  • This function is a code smell as it introduces temporal coupling, but that's not what you meant :) – Wayne Werner Mar 05 '19 at 23:17
  • @dotancohen Just came here because I was googling: "function that can be called multiple times but only executes once", got exactly what I wanted. Don't be so hasty judging merit of questions, other people need different things than you do. – Tomáš Zato Sep 30 '19 at 14:00

6 Answers6

253

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.

Dietrich Epp
  • 113
  • 5
Rufus
  • 1,437
  • 3
  • 9
  • 11
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/90727/discussion-on-answer-by-woofas-what-is-a-term-for-a-function-that-when-called-re). – maple_shaft Mar 07 '19 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".

gerrit
  • 1,010
  • 1
  • 7
  • 21
Neil
  • 22,670
  • 45
  • 76
  • 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. – Jörg W Mittag Mar 04 '19 at 08:28
  • 1
    @JörgWMittag Idempotency is strictly a mathematical term. 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. Clearly that isn't the case as a pure function isn't *only* idempotent, but also has no side effects. As I see it, something is idempotent if you could never receive differing results for the same input after multiple calls. But I suppose we can agree to disagree on that point. – Neil Mar 04 '19 at 08:54
  • 1
    @JörgWMittag, the issue with the term, idempotent, is that it's effectively defined differently in imperative and function programming approaches as purity is assumed for the latter, but not for the former. – David Arno Mar 04 '19 at 09:00
  • 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 Mar 04 '19 at 14:39
  • 7
    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 Mar 04 '19 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 Mar 04 '19 at 22:55
  • 1
    There is the term "nilpotent" for functions where calling them zero times or one time (or 100 times) have the same effect. Idempotence usually implies not being nilpotent, or you would call it nilpotent. – gnasher729 Mar 05 '19 at 07:14
  • 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 Mar 05 '19 at 14:39
  • 2
    In a (not purely functional) programming language, language-level functions from [args] to [retval] are actually mathematical functions from [args,old_global_state] to [retval,new_global_state]. Acknowledging this solves the debate going on here. – R.. GitHub STOP HELPING ICE Mar 06 '19 at 19:48
  • This is not true even from a mathematical point of view: idempotence only makes sense for a function that has the same domain and codomain, e.g. `int -> int`, `String -> String` , `User -> User`. That is orthogonal to purity and if this definition of purity were correct a function like `len: String -> int` (which just gives the length of the input string) would not be pure! – Joseph Cooper Oct 04 '22 at 13:23
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
Tezra
  • 238
  • 1
  • 10
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.

user1717828
  • 213
  • 1
  • 8
  • 2
    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 Mar 04 '19 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 :-) – user1717828 Mar 05 '19 at 01: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().

Stephen Quan
  • 201
  • 1
  • 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. – Draco18s no longer trusts SE Mar 04 '19 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 Mar 05 '19 at 05:59
3

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.

Davislor
  • 1,513
  • 10
  • 13
  • 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. – Carl Witthoft Mar 06 '19 at 15:17