Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
    
Sounds very much like homework. – gnasher729 Jul 3 '15 at 22:42
up vote 59 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
19  
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
8  
@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
3  
@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
4  
@Zachary, please see the last bullet point in my answer. What you are referring to is idempotent behaviour (or the lack thereof). That does not tell you anything about side effects. Checking the system clock is not a side-effect; in fact, any function or method prefixed with the word "get" is one that you should reasonably expect not to have any side effects. – Aaronaught Feb 15 '11 at 16:03

Any operation which modifies the state of the computer or which interacts with the outside world is said to have a side effect. See Wikipedia on Side Effect.

For example, this function has no side effects. Its result depends only on its input arguments, and nothing about the state of the program or its environment changes when it is called:

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++; }
void set_n(int newN) { 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
3  
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

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
    
In my humble opinion, this should be the accepted answer. The concept of a side effect only even makes sense in terms of mathematical functions. A procedure is designed to simply group a set of instructions in a structured way while allowing you to jump to that set from anywhere and back conveniently. There's no primary intended effect and side ones. You could maybe say throwing an exception is a side effect of a procedure, as it breaks the intent of the procedure which is to pop you back to where you left off and continue execution form there. – Didier A. Jul 22 at 17:04

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 '14 at 22:03

In computer science, a function or expression is said to have a side effect if it modifies some state or has an observable interaction with calling functions or the outside world.

From Wikipedia - Side Effect

A function, in the mathematical sense, is a mapping from input to output. The intended effect of calling a function is for it to map the input to the output it returns. If the function does anything else, it doesn't matter what, but if it has any behavior that is not mapping the input to the output, that behavior is known to be a side effect.

In more general term, a side effect is any effect which is not the intended effect of the designer of the construct.

An effect is anything that affects an actor. If I call a function that sends my girlfriend a breakup text message, that affects a bunch of actors, me, her, the cell phone company's network, etc. The only intended effect of calling a side-effect free function, is for the function to return me a mapping from my input. So for:

   public void SendBreakupTextMessage() {
        Messaging.send("I'm breaking up with you!")
   }

If this is intended to be a function, then the only thing it should do is return void. If it was side-effect free, it should not actually send the text message.

In most programming language, there is no construct for a mathematical function. No construct is intended to be used as such. That's why most languages say you have methods or procedures. By design, those are intended to be able to do many more effects. In common programming parlance, no one really cares about the intent of what a method or a procedure was, so when someone says this function has side-effect, they effectively mean, this construct does not behave like a mathematical function. And when someone says this function is side-effect free, they mean, this construct effectively behaves like a mathematical function.

A pure function is always side effect free, by definition. A pure function, is a way to say, this function, even though it's using a construct that allows more effects, only has as effect an equal one to that of a mathematical function.

I challenge anyone to tell me when a side-effect free function would not be pure. Unless the primary intended effect of the context of the sentence using the term pure and side effect free are not that of the mathematical intended effect of a function, then those are always equal.

As such, sometimes, though more rarely, and I believe this is the distinction lacking and also misguiding people (as that is not the most common assumption) in the accepted answer, but sometimes it is assumed that the intended effect of a programming function is to map input to output, where input is not constrained to the explicit parameters of the function, but output is constrained to the explicit return value. If you assume that is the intended effect, then a function reading a file and returning a different result based on what is in the file is still side-effect free, as you allowed inputs to come from other places in your intended effect.

So, why is this all important?

It's all about control and keeping it. If you call a function, and it does something else then return a value, it is hard to reason about its behavior. You will need to go look inside the function for the actual code to guess what it is doing and assert its correctness. The ideal situation, is that it is very clear and easy to know what is the input the function is using and that it isn't doing anything else then returning an output for it. You can relax this a little, and say that knowing exactly what input it is using isn't as helpful as being certain it is not doing anything else you might not be aware of then returning a value, so maybe you are satisfied with only enforcing that it doesn't do anything else then map input, no matter where it gets it from, to output.

In almost all cases, the point of a program is to have effects other then mapping things going in to things coming out. The idea of controlling the side-effect is that you can organize code in a way that is easier to understand and reason about. If you put all the side effect together, in a place that is very explicit and central, it's easy to know where to look and trust that this is all that's happening, no more. If you have the input be very explicit too, it helps test the behavior for different input, and it's easier to use, since you don't need to change the input in a lot of different places, some which might not be obvious, just to get what you want.

Because the most helpful to understand, reason and control the behavior of a program is to have all input clearly grouped together and explicit, as well as have all side-effect be grouped together and explicit, this is generally what people talk about when they say side-effect, pure, etc.

Because the most helpful is the grouping of the side-effects and their explicitness, sometimes people will only mean that, and distinguish it by saying it is not pure, but still "side-effect" free. But side-effect is relative to the assumed "intended primary effect", so it's a contextual term. This I find is less often used, though surprisingly it is talked about a lot in this thread.

Finally, idempotent means calling this function many times with the same inputs (doesn't matter where they come from) will always result in the same effects (side effect or not).

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
9  
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
1  
Printing to the console is a side effect. It is not hidden. From Wikipedia: "In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world." – user40980 Jul 3 '15 at 13:53

protected by gnat Jul 3 '15 at 13:49

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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