Side Effects

Arithmetic operations are referentially transparent: 5*5 can be replaced by 25, for instance. In fact, all functions in the mathematical sense are referentially transparent: sin(x) is transparent, since it will always give the same result for each particular x.

Assignments are not transparent. For instance, the C expression

x = x + 1 changes the value assigned to the variable x.

Assuming x initially has value 10, two consecutive evaluations of the expression yield, respectively, 11 and 12. Clearly, replacing x = x + 1 with either 11 or 12 gives a program with different meaning, and so the expression is not referentially transparent.

However, calling a function such as

int plusone(int x) {return x+1;}

is transparent, as it will not implicitly change the input x and thus has no such side effects.

today() is not transparent, as if you evaluate it and replace it by its value (say, “Jan 1, 2001”), you don’t get the same result as you will if you run it tomorrow. This is because it depends on a state (the time).

It is important to note that programs free of side effects are more scalable, since at the program level they exhibit the so-called shared-nothing architecture, that is, it does not share state. And to find out more about state, see my post Much Ado About State.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s