Function Purity


Function purity is a programming concept which explores the side-effects of a given function.

A "pure" function is one that takes some input and returns some output without having any side effects (essentially, the state of the script should be exactly the same after running the function). For example:

function example_pure(temp.a)
{
	temp.b = temp.a * 2;
	return temp.b + 2;
}

A pure function should always give the same output given the same input values. For instance, the above function will always return 14 if you give it the input value 6. Typically this means that a function:

Here are some built-in examples of pure functions: sin(x), str.length().

An "impure" function, on the other hand, is one that may give a different output on the same input, or has side effects which affect other areas of the script after the function has been run, e.g.

function example_impure(temp.a)
{
	player.chat = "Impure!!";
	return temp.a + 2;
}

This function is impure because the script has changed something outside of the function, in this example, player.chat.

Here are some examples of built-in impure functions: echo(x), random().

Generally, a good way to make clearer code is to have as many pure functions as possible, and only have the impure function be all the way at the outside of your pure function calls.

Related

The following related articles are recommended:

Categories

CategoryMiscellaneous

There are no comments on this page. [Add comment]

Valid XHTML 1.0 Transitional :: Valid CSS :: Powered by WikkaWiki