Side Effects in programming

According to Wikipedia, a function or expression is said to have a side effect if it modifies some state outside its local environment. Let’s understand this in depth by examples.

To understand side effects, first, we should know what “state” is. In layman terms, the state refers to the value of the variable at any given point in the program like x=2.

Now, the above Wikipedia definition might have started to make some sense. If not, don’t worry, see the figure below.

In this figure, we have a variable x that is outside the scope of two functions. Clearly, after the Function_2 call, the value of x changes which means that Function_2, other than returning value(if any), is interacting with variables outside its local environment and thus has a side effect.

In general, any lasting effect that occurs in a function, not through its return value, is called a side effect. Not through its return value means if we assign x=Function_1(), this will clearly change the value of x but this is not a side effect. For side effect, the change should occur inside a function.

Common ways to have side effects:

  1. Modifying a non-local variable: Let’s understand by an example

    The x in the square() function is local to its scope so no change in outside x. Global in square_side_effect() makes x global so any change in x will change it in whole code (outside function scope) so the square_side_effect function() is not pure(has side effects).
  2. Changing the value of a mutable object: Let’s take Lists which is a mutable object.

    Clearly, after calling list_side_effect(), the value of lst changes so, list_side has side effects.
  3. Performing Input/Output operations: This doesn’t change any objects or variable value, but it does have a potential lasting effect outside the function call because a person might see the output and be influenced by it.
  4. Calling other side-effect functions

Now, you might have got some feeling about the side effects. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Leave a Reply