Jump to content

Side effect (computer science)

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 64.105.112.xxx (talk) at 20:14, 11 January 2002. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

A side effect is when a function modifies something in its (or another scope's) internal state. For example, any of the following can be side effects:


1) Modifying a global variable.

2) Modifying a static variable.

3) Modifying a parameter.

4) Writing something to the display.

5) Saving something to a file.

6) Using another side-effecting source for your data.


Side-effects aren't considered good because they make a program's behavior more difficult to understand.


A function that uses side-effects will be referred to as a referentially opaque function, and one that doesn't will be referentially transparent. For simplicity's sake, we'll say that a referentially transparent function is one that given the same parameters will always return the same result.


As an example, let's use 2 functions, one which is referentially opaque, and the other which is referentially transparent:




globalValue = 0;

integer function rq(integer x)

begin

  globalValue = globalValue + 1;
  return x + globalValue;

end




integer function rt(integer x)

begin

  return x + 1;

end





Now, rt is referentially transparent, which means that rt(x) = rt(x) as long as x is the same value. For instance, rt(6) = rt(6) = 7, rt(4) = rt(3+1) = 5, and so on.


However, we can't say any such thing for rq because it uses a global value which it modifies.


So, how is this a bad thing? Well let's say we want to do some reasoning about the following chunk of code:


integer p = rq(x) + rq(y) * (rq(x) - rq(x));


Now, right off-hand, one would be tempted to simplify this line of code to:


integer p = rq(x) + rq(y) * (0) =

integer p = rq(x);


However, this will not work for rq because rq(x) <> rq(x)! Remember, that the return

value of rq is based on a global value which isn't passed in and which gets modified all

over the place. This goes against common sense since anything minus itself SHOULD be 0. We just lost any attempt at mathematical validity!


This however will work for rt, because it is a referentially transparent function. Therefore we can reason about our code which will lead to more robust programs, the possibility of finding bugs that we couldn't hope to find by testing, and even the possibility of seeing opportunities for optimization.