Showing posts with label Side Effects. Show all posts
Showing posts with label Side Effects. Show all posts

Tuesday, February 15, 2011

Programming Side Effects

Alright, so it's not often I actually benefit from programming classes, but every once in a while, a teacher sparks off an idea. Today that idea was side effects! This is a concept related to style and modularity, as well as a little bit of math.

Traditionally in math, when you call a function, you get a value back, f(x) = y. Going further, these results should be communicative, f(x) + g(x) = y and g(x) + f(x) = y. In programming however, this is not the case. All sorts of additional values can come in and contaminate the purity of the math based idea of functions, global variables like time and random seeds, and nearby variables that track the internal state of a class. All of these affecting values are called "Side Effects".

Here's a quick example:

#include <stdio.h>

int a = 0;

int Func1()
{
 a += 2;
 return a;
}
int Func2()
{
 a *= 4;
 return a;
}

int main()
{
 printf("%d\n", Func1() + Func2() );
 printf("%d\n", Func2() + Func1() );
}

In this case, you can easily see the side effect variable 'a', which completely destroys the predictability of the code. The problem is, this functionality is incredibly important to larger more complicated programs, which is why large amounts of effort is expended to do such things safely. This results in properties, get/set methods, and all manner of other things.

So it's something to think about when coding and to avoid if you can. It may even be a good thing to mark them down and keep track of in the comment docs, so you know which functions are less likely to be causing issues.

Just some food for thought =D