Naming Functions – Term for Function with Same Effect When Called Repeatedly

functionsnaming

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

Best Answer

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.

Related Topic