141

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.

1
  • The side effect is the complement of the intended effect.
    – Géry Ogam
    Jun 28, 2021 at 16:02

8 Answers 8

156

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.

28
  • 55
    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. Jan 26, 2011 at 22:18
  • 15
    @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. Jan 26, 2011 at 23:07
  • 9
    @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, 2011 at 0:22
  • 7
    @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, 2011 at 4:13
  • 5
    @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, 2011 at 16:03
54

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); }
5
  • 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, 2011 at 20:14
  • 6
    It's not about being idempotent. The fact that it produces output means that it has a side effect. Jan 26, 2011 at 23:42
  • In some system, invoking square(x) might cause the module where the function is defined to be loaded from disk. Should this be considered side-effect? After all, this mens that the (first) call takes unexpectedly long, that RAM usage goes up, etc. Jun 20, 2017 at 16:31
  • 2
    @HagenvonEitzen Every operation actually makes changes to the computer's state (CPU registers, memory, power consumption, heat, etc.). "Side effect" usually refers to an imaginary idealized execution environment where nothing about that environment changes unless the program explicitly changes it. But if you are calling square(x) because you want that external computer state to change, you could consider that to be a side effect. Oct 6, 2017 at 15:43
  • 2
    For me the first illustration makes perfect sense. However, the second one less so. I believe side-effect should be defined in relation to a certain environment/scope. If you consider the whole universe, there’s no such thing as no side-effect. Even if you confine it to the computer, your function will affect another processes in that the CPU will not behave the same. If you confine the scope to things accessible in a local function scope, then we got something to talk about.
    – funct7
    Oct 14, 2019 at 22:43
41

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.
2
  • 9
    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, 2016 at 17:04
  • 1
    This is the best answer I have came across the internet. Cheers! Dec 20, 2019 at 18:48
6

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.

6
  • 2
    I don't think that this is a good universal definition. Many programmers intentionally use constructs specifically for their side effect.
    – CB Bailey
    Jan 26, 2011 at 19:57
  • @Charles: Fair enough. In that case, how would you define it? Jan 26, 2011 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.
    – CB Bailey
    Jan 26, 2011 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, 2011 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.
    – CB Bailey
    Jan 27, 2011 at 7:36
5

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).

6
  • I think a big problem with explaining side effects is that until you've used a language like Ocaml or Haskell, it can be very hard to reason about side-effect free (almost!) programming.
    – Jamie S
    Apr 4, 2018 at 16:06
  • 1
    Excellent answer, except for the final sentence: idempotent means that multiple calls with the same inputs have the same intended effect as a single one (i.e. side effect are excluded from the definition), cf. RFC 7231, Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, § 4.2.2 Idempotent Methods.
    – Géry Ogam
    Jun 28, 2021 at 15:56
  • Yes I think my wording might have been a bit confusing. What I meant is that calling a function many times with the same input will always result in the same effects as calling it only once, and that the effects can be intended or side-effects, so an idempotent function doesn't have to be side-effect free, all it needs is that as you said, repeated execution with the same input do not repeat the effects, the effects happen only once per unique combination of input.
    – Didier A.
    Jun 29, 2021 at 7:49
  • I think that you are giving a stronger definition of idempotence than the actual definition. You seem to require that only the first call has an effect (intended and side effect) and subsequent calls have no effect, while the actual definition requires that the sum of the intended effects of each call is equal to the intended effect of the first call. For instance a safe request initiated by selecting an advertisement on the Web which has the side effect of charging an advertising account would not be idempotent under your definition.
    – Géry Ogam
    Jun 29, 2021 at 21:02
  • I see what you mean, yes you're correct, that's an important detail. As long as repeated calls result in the same intended effect that calling it once should have, it is idempotent. I think the part I'm not sure is if this only applies to back to back repeats, or even with other interleaved operations. Like f(x), f(x) results in the same intended effect as f(x) is idempotent, but what if f(x), g(x), f(x) does not result in the same intended effect? Like arguably, because f(x) does something based on some state that g(x) would change, than is f still idempotent?
    – Didier A.
    Jul 1, 2021 at 1:24
3

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.

2
  • 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, 2014 at 22:03
  • I think that some of the pre-gui programming languages like MS-BASIC and QBasic may have been as close to a 'side effect only' language as you can get. And yes you can have both internal and external side effects.
    – James K
    Jun 27, 2017 at 3:17
0

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.

8
  • But if message comes in as reference and you change message in your method that may would be a side effect. Am I correct? Jan 26, 2011 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.
    – CB Bailey
    Jan 26, 2011 at 19:59
  • @Charles - I agree, although the original example was not as clear as the current one. Jan 26, 2011 at 20:01
  • @Amir - Well, that really depends on the language. If this were C# this would not be considered a side effect. Jan 26, 2011 at 20:03
  • @ChaosPandion: Personally, I disagree. The original example was much simpler and clearer.
    – CB Bailey
    Jan 26, 2011 at 20:03
-2

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.

5
  • 10
    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, 2011 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, 2015 at 13:53
  • Side effects are how non functions (ie procedures) get any work done. X=1; X=Y(10) are two pure functions. When you step outside of the "x = whatever" realm, whether to write output to the screen|drive|printer|led or read input outeside the "x=y" format or simply change the value of a variable from one thing to another, it's a side effect.
    – James K
    Jun 27, 2017 at 2:23
  • I think that by 'hidden', he means non-obvious. Like in x=f(y,z) x can be assumed to be based on y and z. Whereas proc(x,y,z) tells you nothing about what's going on. Every varable could be changed, or none. Proc could be an analog to f, or completely unrelated. A pure function has a single answer: 'x'. Go beyond that, it's a side effect. Wholly intended, but side effects.
    – James K
    Jun 27, 2017 at 2:37
  • Just like to understand 0, you must first understand 1: To understand side effects you must first understand functions.
    – James K
    Jun 27, 2017 at 2:41

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