7

Most tutorials/articles/books talk about side effects when presenting functional programming. Take this Python code:

def isPrime(n):
    k = 2
    while k < n:
        if n % k == 0:
            return False
        k += 1
    return True

The text says that the above function has local side effects, and I don't understand that. I see that the variable "k" is changing, I don't understand what bad comes out of it.

Can someone please give a clear example of bad side effect, and how it is avoided by functional programming?

blackened
  • 387
  • 6
  • 16
  • W.r.t. side-effects, note that FP vs. procedural programming [is orthogonal to IP vs. DP](http://stackoverflow.com/questions/602444/what-is-functional-declarative-and-imperative-programming/8357604#8357604). – Shelby Moore III Dec 08 '11 at 01:16

2 Answers2

16

The text you're referring to is right, changing a local variable is considered a side effect.

It doesn't say that this is a bad thing necessarily. It is just not functional programming. In pure functional programming languages you would write the loop in a recursive way, eliminating the need for changing variables.

Writing functions like these (that have no observable side effects) is a fine practice in any language, it is just not functional programming.

Edit: Now I see your remark about "bad" side effects. I would not say that side effects are bad. In most mainstream languages, it is hard to program without them, and I think that many programmers think in terms of side effects. But in large software projects, relying too much on side effects can make your life pretty miserable. Here's a nice example involving singletons (the ultimate way to cause side effects)

In a language that forbids side effects, there are less surprises for you as a programmer, but also for the compiler. Pure functional code is easier to analyze and paralellize, and is, at least theoretically, easier to optimize by the compiler.

thSoft
  • 21,755
  • 5
  • 88
  • 103
3

Side-effects (specifically not having referential transparency) make the result of your code depend on the order of execution of the statements. Thus a change to the order of invoking some pair of function calls, could possibly alter behavior in a disconnected area of your program. This is because they weren't really disconnected, due to the mutual sharing of side-effects.

This makes the decomposition of your program difficult to implausible, thus frustrating attempts to compose your existing code with new code, or otherwise isolate and separate out the functionality of any portion of your code. In other words, side-effects are like Rigor Mortis glue that spills on everything and causes it to be one impenetrable monolithic spaghetti. Try to pull out one noodle, without causing a cascade of disturbance to most the other noodles.

Community
  • 1
  • 1
Shelby Moore III
  • 6,063
  • 1
  • 33
  • 36