0
votes

I am learning about side-effects in functional programming. I know that external effects are effects that are observable outside the function, whereas internal effects are not visible from the outside. I would like to know whether modifying local variables is an external or internal effect.

Since local variables are only accessible within the function and are not visible to the outside world, I believe that modifying local variables is an example of an internal effect, since it's not observable to the outside world.

However, I am not sure if my reasoning is correct. Any insights are appreciated.

1

1 Answers

2
votes

It depends.

As long as the function in question always returns the same values for the same inputs then modified local variables are internal: the caller can't tell if local state is modified or not. But if the modified locals are stored in a closure and the function returns different values based on the state of that local then even though the caller cannot directly observe the closed over variable the side-effect is external.

As to whether it's a good idea to modify local variables, well, I'm no purist but most of the arguments in favor of immutability still apply to locals as well as globals. On the other hand, in a short, clear function contorting the code just to avoid mutation seems like overkill. This is somewhat language-dependent. Use your best judgement.