135

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.

Amir Rezaei
  • 10,938
  • 6
  • 61
  • 86

8 Answers8

153

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.

Aaronaught
  • 44,005
  • 10
  • 92
  • 126
  • 1
    And the reason the word exist is to contrast it with Immutable/Stateless as well as the difficulty side effects present in trying to understand code. A program written without side effects would confine understanding to each function since each function would not do anything else besides its function. You would not have to understand a whole chain of events involving class attributes. – zhenka Jan 26 '11 at 22:18
  • 53
    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
  • 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. – Mason Wheeler Jan 26 '11 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 '11 at 00:22
  • @S.Lott: What "crypto-assignment statement"? I'm unaware of any language feature of any language that allows "crypto-assignment", or assignment without the use of either a plain old assignment operator or its slightly heavier cousin, the data copy routine. It's simply that these assignment operations tend to be contained within subroutines and methods, due to programmers employing abstractions and building software in layers. The simple fact is that the generation of "side-effects" is the entire point of using any computer program in the first place. – Mason Wheeler Jan 27 '11 at 01:08
  • 1
    @Mason: I could be wrong, but I believe that by "crypto assignment" he is simply referring to functions with side-effects, and the fact that the assignments that take place therein are indirect (and thus "hidden"). I'm not that much of a purist myself, but he is right, in a sense; it's easier to reason about the state of a program when every side effect happens within an explicit assignment. – Aaronaught Jan 27 '11 at 03:28
  • 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 '11 at 04:13
  • 4
    @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
  • It can also be something that refrences the outside world. getTimeOfDay() for example has a side effect, it checks the system clock. If you call it 10 times you will get 10 different return values. – Zachary K Feb 15 '11 at 15:15
  • 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 '11 at 16:03
  • 1
    @aaronaught, to complete this answer, maybe you could add a third bullet point mentioning purity, which (as I understand it) is *both* being idempotent *and* avoiding side-effects? – Benjol Aug 05 '11 at 07:40
  • 2
    This is incorrect. In some languages, access can be a side effect. In C, accessing a `volatile`-qualified object is a side effect. With some kinds of hardware, if you read a register, it is externally visible that you have done so. Checking the system time could increment some performance counter register which counts how many times the clock has been accessed. The CPU might have to write to some GPIO line to get the clock reading. An LED connected to the RTC could flash indicating "RTC accessed". All interactions with h/w should be regarded as side effects. At least until debugged! :) – Kaz Feb 03 '13 at 04:32
  • 3
    "...a pure function, which is a function that is (a) idempotent..." I don't agree with this. A function `f` that multiplies a number by 2 can be pure, but is not idempotent. `f(3) == 6`, but `f(f(3)) == 12`. Idempotency would require `f(f(x)) == f(x)`. If `f` multiplied a number by 1, then it would be idempotent. I think you mean "referentially transparent" instead place of "idempotent." – Gary Fixler Apr 27 '15 at 08:30
  • 2
    This seems very incomplete and even somewhat wrong to me. Getting the system time and date is definitely a side effect, unless you passed in to the function a clock. – Didier A. Jul 22 '16 at 17:09
  • 3
    "the modification of some kind of state" I would rephrase this to say "the modification of any state *outside the scope of the currently executing function or method*. If you have a function that has variables for the function's current state, such as `i` in a standard `for` loop, we don't call the modification of `i` a "side effect". I think this answer could also be improved by making it clear that the "effect" of a function is its return value. All other state changes are therefore "side effects". – zzzzBov Jul 22 '16 at 19:00
  • @S.Lott: "It existed long before FP.": Even if the term had not been invented in the context of FP (I have no idea in which context it was first used), it seems difficult that it may have existed long before FP, since FP was one of the first programming paradigm that have been invented. – Giorgio Apr 01 '17 at 20:39
  • 2
    I am pretty confident @aaronaught is not using the word 'idempotent' correctly in this answer. Just in case anyone else is second-guessing himself about knowing what idempotence means. – Menno van den Heuvel Jun 20 '17 at 11:45
  • As others have said, this definition of pure function incorrectly requires idempotency. `f(n)=n+1` isn't idempotent, since `f(f(n)) != f(n)` for any `n`. But it still satisfies 1. in the definition linked, since it always returns the same value. So pure does not imply idempotent. Moreover, idempotent doesn't even imply pure (eg., idempotent write is still a write). So I agree idempotent has nothing to do with side effects, but it also has nothing to do with pure functions, so even the top answer is getting it wrong. – stewSquared Jul 14 '20 at 20:06
  • @Benjol purity does not require idempotence. Consider that the "increment" function is pure, yet not idempotent. – stewSquared Jul 14 '20 at 20:09
  • @stewSquared, you'd have to show me the signature of your increment function in order to be able to answer this comment. Purity implies idempotence. – Benjol Jul 28 '20 at 09:02
  • @Benjol The example I used, `f(n)=n+1` is `Int => Int`. `f(f(0))` is not the same as `f(0)`, so `f` is not idempotent. If this example is not enough, the definition of purity is linked above. It does not follow that any pure function is idempotent. – stewSquared Jul 29 '20 at 16:11
  • The problem is that the OP reads the definition "return value is the same for the same argument" and summarizes as "idempotent". While all idempotent functions return the same value for the same argument, not all functions that return the same value for the same argument are idempotent. – stewSquared Jul 29 '20 at 16:16
  • "multiply by zero" is pure. "multiply by two" is pure. But only the former is idempotent, since multiplying by zero twice is the same as multiplying by zero once, but doubling twice is not necessarily the same as doubling once. – stewSquared Jul 29 '20 at 16:23
  • @stewSquared, ok I'd actually only read the comment where you @ me, which is why I didn't understand. Better understood now. I guess idempotence is actually only interesting in the context of something which has a state that can be changed. – Benjol Jul 30 '20 at 09:40
  • Side effects introduce time to your code. If time matters it makes a difference how often a function is invoked or if it is invoked at all. Just because some impure functions are idempotent doesn't mean both properties are orthogonal. Side effects hamper idempotence! – woo Oct 13 '20 at 13:46
  • This is answer is misleading. As [Didier A.](https://softwareengineering.stackexchange.com/a/325520/184279) explained: ‘In more general term, a side effect is any effect which is not the intended effect of the designer of the construct.’ So the intended/side effect property is **relative to a particular construct.** For instance, a state change is a side effect *for a function,* but not necessarily *for a procedure,* for which it can be an intended effect. – Géry Ogam Jun 29 '21 at 22:31
  • So equating ‘state change’ with ’side effect’ like in this answer is a misuse of language. This answer’s statement ‘A side effect does not have to be hidden or unexpected’ really means ‘A *state change* does not have to be hidden or unexpected’, i.e. ‘A *state change* does not have to be a side effect’, which is correct, e.g. for a procedure. – Géry Ogam Jun 29 '21 at 22:31
  • 1
    By itself, "changing the value of a variable" does not qualify as a side effect. This answer lacks the crucial final phrase from the first sentence of the cited Wikipedia article: "in computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) *outside its local environment*" [emphasis mine]. – FMc Mar 29 '22 at 04:31
53

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); }
Kristopher Johnson
  • 1,719
  • 4
  • 15
  • 15
  • 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
  • 6
    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
  • 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. – Hagen von Eitzen Jun 20 '17 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. – Kristopher Johnson Oct 06 '17 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 '19 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.
Giorgio
  • 19,486
  • 16
  • 84
  • 135
  • 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 '16 at 17:04
  • 1
    This is the best answer I have came across the internet. Cheers! – Govinda Malavipathirana Dec 20 '19 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.

FrustratedWithFormsDesigner
  • 46,105
  • 7
  • 126
  • 176
  • 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 '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. – CB 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 00: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 '11 at 07:36
  • @CharlesBailey The side effect is not in terms of the intent of the programmer, but in terms of the assumptions of a function. A lot of people take drugs for their side effect consciously too, but it's not the primary intended usage. A mathematical function is not intended to do anything outside of itself, that is the normal effect. If you do more then that, it is a side effect. – Didier A. Jul 22 '16 at 16:59
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).

Didier A.
  • 1,327
  • 14
  • 10
  • 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 04 '18 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](https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.2). – Géry Ogam Jun 28 '21 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 '21 at 07: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 '21 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 01 '21 at 01:24
  • This answer seems to semi-endorse the view that a side-effect-free function could read from the file system? That's a bridge too far. If we can read the file system, can we read from a DB, make HTTP requests, etc? In common usage, I would never describe a function engaged in IO as side-effect-free, and I think that view is widely held -- for example, the first paragraph of the cited Wikipedia article. – FMc Mar 29 '22 at 04:26
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.

indyK1ng
  • 815
  • 5
  • 11
  • 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 06 '14 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 '17 at 03: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.

ChaosPandion
  • 6,305
  • 2
  • 33
  • 33
  • 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. – CB 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. – CB Bailey Jan 26 '11 at 20:03
  • @Chad: His original example was fine. Your comment is wrong. As I responded to your answer, side effects are simply the modification of state; they need not be hidden or unexpected. – Aaronaught Jan 26 '11 at 20:04
  • @Charles - I tend to believe that a broader audience will understand what a side effect is when changing the state of some hypothetical object. – ChaosPandion Jan 26 '11 at 20:08
  • The fact that the Debug output is changed is a side effect as well, correct? – spirc Dec 01 '15 at 00:27
-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.

CaffGeek
  • 8,033
  • 5
  • 32
  • 38
  • 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 '11 at 20:03
  • 1
    Printing to the console is a side effect. It is not hidden. From [Wikipedia](https://en.wikipedia.org/wiki/Side_effect_(computer_science)): "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***." –  Jul 03 '15 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 '17 at 02: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 '17 at 02:37
  • Just like to understand 0, you must first understand 1: To understand side effects you must first understand functions. – James K Jun 27 '17 at 02:41