Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I haven’t clearly understood the concept of side effect.

  • What is side effect in programming?
  • Is it programming language dependent?
  • Is there such a thing as external and internal side effects?

Please give some example of causes that create side effects.

share|improve this question

7 Answers 7

up vote 34 down vote accepted

A side effect refers simply to the modification of some kind of state - for instance:

  • Changing the value of a variable;
  • Writing some data to disk;
  • Enabling or disabling a button in the User Interface.

Contrary to what some people seem to be saying:

  • A side effect does not have to be hidden or unexpected (it can be, but that has nothing to do with the definition as it applies to computer science);

  • A side effect has nothing to do with idempotency. An idempotent function can have side effects, and a non-idempotent function may have no side effects (such as getting the current system date and time).

It's really very simple. Side effect = changing something somewhere.

P.S. As commenter benjol points out, several people may be conflating the definition of a side effect with the definition of a pure function, which is a function that is (a) idempotent and (b) has no side-effects. One does not imply the other in general computer science, but functional programming languages will typically tend to enforce both constraints.

share|improve this answer
11  
The phrase "side effect" makes it sound like something else is being changed other than what was intended. In medicine, a drug will have a main effect of reducing pain, and sometimes a side-effect of causing nose-bleeds, dizziness, etc... the purpose of the drug is not to cause nose-bleeds but sometimes that happens as an unintended extra result. –  FrustratedWithFormsDesigner Jan 26 '11 at 22:18
3  
@Frustrated: +1. Whenever I see that term I can't help but wonder if it wasn't chosen by FP advocates to create precisely that subtly sinister connotation. –  Mason Wheeler Jan 26 '11 at 23:07
2  
@Mason Wheeler. It existed long before FP. And it's not a subtly sinister connotation. It's flat-out evil and always has been. For the 3 decades I've been coding, the "crypto-assignment" statement -- the side-effect -- has been troubling people. A plain old assignment statement is much easier to cope with. –  S.Lott Jan 27 '11 at 0:22
4  
@Mason Wheeler: In C. ++a. Does not look like assignment. b = ++a; has two side effects. The obvious one and the crypto-assignment of a. That's the kind of thing that is a side-effect that (to some) is desirable. But has been called a side-effect for my entire career to make it not subtle. –  S.Lott Jan 27 '11 at 4:13
2  
@S.Lott: Oh, right. C++. Sorry that I didn't remember about that rather obvious example; I haven't used C++ since college and I've been mostly successful at blocking out the traumatic memories. –  Mason Wheeler Jan 27 '11 at 14:20

Any operation which modifies the state of the computer or which interacts with the outside world is said to have a side effect. See http://en.wikipedia.org/wiki/Side_effect_(computer_science).

For example, this function has no side effects. You can call it as often as you like, and nothing about the state of the program changes:

int square(int x) { return x * x; }

In contrast, calling these functions will give you different results depending upon the order in which you call them, because they change something about the state of the computer:

int n = 0;
int next_n() { return n++; }
int set_n(int newN) { return n = newN; }      

This function has the side effect of writing data to output. You don't call the function because you want its return value; you call it because you want the effect that it has on the "outside world":

int Write(const char* s) { return printf("Output: %s\n", s); }
share|improve this answer
1  
This is a good definition, but I'm not crazy about the elaboration - just as in Thorbjørn's answer, part of it seems to be conflating the issue of side effects with that of idempotent functions; as your Write example demonstrates, having side effects does not imply that the function ever changes its output with respect to its inputs, or even that its output depends on the input at all. –  Aaronaught Jan 26 '11 at 20:14
1  
It's not about being idempotent. The fact that it produces output means that it has a side effect. –  Kristopher Johnson Jan 26 '11 at 23:42

A side-effect is when an operation has an effect on a variable/object that is outside the intended usage.

It can happen when you make a call to a complex function that has a side-effect of altering some global variable, even though that was not the reason you called it (maybe you called it to extract something from a database).

I admit I'm having trouble coming up with a simple example that doesn't look totally contrived, and examples from stuff I've worked on are waaaay too long to post here (and since it's work related, I probably shouldn't anyway).

One example I've seen (a while ago) was a function that opened a database connection if the connection was in a closed state. The problem was that it was supposed to close the connection at the end of the function, but the developer forgot to add that code. So here, there was an unintended side effect: calling a procedure was supposed to only do a query and the side effect was that the connection remained open and if the function was called twice in a row, an error would be raised saying the connection was already open.


Ok, so since everyone's giving examples now, I think I will too ;)

/*code is PL/SQL-styled pseudo-code because that's what's on my mind right now*/

g_some_global int := 0; --define a globally accessible variable somewhere.

function do_task_x(in_a in number) is
begin
    b := calculate_magic(in_a);
    if b mod 2 == 0 then
        g_some_global := g_some_global + b;
    end if;
    return (b * 2.3);
end;

The function do_task_x has a primary effect of returning the result of some calculations, and a side effect of possibly modifying a global variable.

Of course, which is the primary and which is the side effect could be open to interpretation and might depend on actual usage. If I call this function for the purpose of modifying the global and I discard the returned value than I'd say that modifying the global is the primary effect.

share|improve this answer
2  
I don't think that this is a good universal definition. Many programmers intentionally use constructs specifically for their side effect. –  Charles Bailey Jan 26 '11 at 19:57
    
@Charles: Fair enough. In that case, how would you define it? –  FrustratedWithFormsDesigner Jan 26 '11 at 19:59
2  
I think that @KristopherJohnson has the clearest definition. Anything that alters that state of the program or its environment or produces a real world effect such as generating output. –  Charles Bailey Jan 26 '11 at 20:02
    
@Charles Bailey: That doesn't change the definition. Using things for the side-effect is fine. As long as you understand that there's a side-effect. It doesn't alter anything about this definition. –  S.Lott Jan 27 '11 at 0:24
1  
@SLott: The definition in this answer (i.e. the first paragraph) includes the clause: "outside the intended usage". I think that my comment was fair. –  Charles Bailey Jan 27 '11 at 7:36

In programming a side effect is when a procedure changes a variable from outside its scope. Side effects are not language dependent. There are some classes of languages which aim to eliminate side effects (pure functional languages), but I'm not sure if there are any which require side effects, but I could be wrong.

As far as I know, there are no internal and external side effects.

share|improve this answer
    
To be more precise, pure functional languages clearly separate side-effect free code from other code, whereas other languages have no mechanism to distinguish between pure and impure code. Most programs need to have side-effects to be of any use. –  Giorgio Nov 6 at 22:03

I think that the existing answers are quite good. I would like to elaborate on some aspects that IMO have not been stressed enough.

In mathematics a function is just a mapping from a tuple of values to a value. So, given a function f and a value x, f(x) will always be the same result y. You may well replace f(x) with y everywhere in an expression and nothing will change.

What is called a function (or procedure) in many programming language is a construct (piece of code) that can be executed because:

  1. It computes a function in the mathematical sense, i.e. given input values, it returns a result, or
  2. It produces some effect, e.g. prints something to the screen, changes a value on a database, launches missiles, sleeps for 10 seconds, sends an SMS.

So effects can be related to state but also to other aspects like firing a missile or pausing execution for a few seconds.

The term side-effect may sound negative but normally the effect of calling a function is the very purpose of the function itself. I suppose that, since the term function was originally used in Mathematics, computing a value is considered to be the primary effect of a function whereas any other effects are considered side-effects. Some programming languages use the term procedure to avoid confusion with functions in the mathematical sense.

Note that

  1. Some procedures are useful for both their return value and their side-effect.
  2. Some procedures only compute a result value and have no other effects. They are often called pure functions because all they do is compute a function in the mathematical sense.
  3. Some procedures, e.g. sleep() in Python, are only useful for their (side) effects, . These are often modeled as functions that return a special value None, or unit or () or ..., which simply indicates that the computation has terminated correctly.
share|improve this answer

Here is a simple example:

int _totalWrites;
void Write(string message)
{
    // Invoking this function has the side effect of 
    // incrementing the value of _totalWrites.
    _totalWrites++;
    Debug.Write(message);
}

The definition of side effect is not specific to programming so simply imagine the side effects of your meds or eating too much food.

share|improve this answer
    
But if message comes in as reference and you change message in your method that may would be a side effect. Am I correct? –  Amir Rezaei Jan 26 '11 at 19:59
    
The fact that the expression x++ modifies the variable x is commonly considered to be a side effect. That value of the expression is the pre-increment value of x; this is the non-side effect part of the expression. –  Charles Bailey Jan 26 '11 at 19:59
    
@Charles - I agree, although the original example was not as clear as the current one. –  ChaosPandion Jan 26 '11 at 20:01
    
@Amir - Well, that really depends on the language. If this were C# this would not be considered a side effect. –  ChaosPandion Jan 26 '11 at 20:03
    
@ChaosPandion: Personally, I disagree. The original example was much simpler and clearer. –  Charles Bailey Jan 26 '11 at 20:03

A side effect is things that happen in code that aren't obviously apparent.

For example lets say you have this class

public class ContrivedRandomGenerator {
   public int Seed { get; set; }

   public int GetRandomValue()
   {
      Random(Seed);
      Seed++;
   }
}

When you initially create the class you give it a seed.

var randomGenerator = new ContrivedRandomGenerator();
randomGenerator.Seed = 15;
randomGenerator.GetRandomValue();

You don't know the internals, you just expect to get a random value, and you would expect the randomGenerator.Seed to still be 15... but it's not.

The function call had the side effect of changing the Seed value.

share|improve this answer
8  
Side effects do not have to be hidden. You're thinking of colloquial or medical usage; in programming, a side effect simply refers to modifying some state. –  Aaronaught Jan 26 '11 at 20:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.