Functional Programming: Side Effects

Most manuals / articles / books talk about side effects when introducing 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 do not understand this. I see that the variable "k" is changing, I do not understand that the bad comes out of it.

Can someone please give a clear example of a bad side effect and how to avoid it with functional programming?

+7
source share
2 answers

The text you are referring to is right; changing a local variable is considered a side effect.

He does not say that it is bad. This is simply not functional programming. In pure functional programming languages, you must write a loop in a recursive manner, eliminating the need for variable changes.

Recording functions like these (which have no observable side effects) are great practice in any language, it's just not functional programming.

Edit: Now I see your comment about the “bad” side effects. I would not say that the side effects are bad. In most major languages, it is difficult to program without them, and I think that many programmers think about side effects. But in large software projects, relying too much on side effects can make your life pretty miserable. Here's a good example involving singletones (the ultimate way to cause side effects)

In a language that prohibits side effects, there are fewer surprises for you as a programmer, but also for the compiler. Pure functional code is easier to parse and paralyze and, at least theoretically, easier to optimize by the compiler.

+16
source

Side effects (in particular, that do not have referential transparency) make the result of your code dependent on the order in which the statements are executed . Thus, changing the order of calls to some function calls can lead to a change in behavior in the disconnected area of ​​your program. This is due to the fact that they were not really disabled due to the mutual exchange of side effects.

This makes it difficult to decompose your program, making it difficult to compile your existing code using new code or otherwise isolate and separate the functionality of any part of your code. In other words, the side effects are similar to Rigor Mortis glue, which spills everything and makes it one impenetrable monolithic spaghetti. Try to pull one noodle without causing a cascade of disruption of most other noodles.

+3
source

All Articles