Written by 4:00 pm Miscellania

Coder’s Vocab #1 : Idempotent

In programming, the term idempotent describes a method that can be called multiple times without changing the result. Sometimes it can be a symptom of madness or incompetence – I’ve seen code where a save() method was called repeatedly "just in case." 

Besides scratching the itch of the insane among us, idempotent routines are important. For a simple example, consider the "Checkout Button" on a typical ecommerce form. Often you will see strong language around the button asking the user to only click the button once – otherwise multiple orders will be placed and all sorts of pain and confusion may result. A common "solution" to this is disabling the button after the first click. A better solution would be writing the routine that is saving the order as an idempotent operation. In other words, it shouldn’t matter how many times you save the order, you’re just saving the same thing. This can be accomplished in myriad ways, from using a "replace into" database query or creating the key once and updating the database against that key. 

Quiz Time! Which of the methods could be described as idempotent?

 1.

function double($x) {
return $x * 2;
}

2.

$x = 2;

3.

$x = md5($x);

 4. 

function append($x,$y){
$x[] = $y
}

Find creatine and protein supplements now. 

Close