Consider this javascript function:
function(){
var someArr = [...];
var someObj = {...};
someArr.forEach(function(item){
if (matchItem(item)){
someObj.callMethod(item.someProp);
}
});
}
Assuming that given code works correctly, let’s take a look at it’s design. As you can notice, someArr.forEach
is passed a callback function. Meanwhile, object someObj
belongs to the scope of that callback. So from inside the callback function we can manipulate someObj
.
I.e., in this case the callback produces side effects.
We could also bind someObj
to this
object of the callback:
function(){
var someArr = [...];
var someObj = {...};
someArr.forEach(
function(item){
if (matchItem(item)){
this.callMethod(item.someProp);
}
},
someObj
);
}
Again, we are producing some side effects here, though in more explicit manner. In general, this approach can not be considered functional, because it violates the no-side-effects principle.
How should we design code in such situations? Which way is more robust? What are the best practices?
Thank you!
5
The Array.prototype.forEach
is meant for side effects, it doesn’t return anything. Whether you like it or not depends on your application, there’s no clear best practice.
Object oriented programming is stateful by design, it’s meant for side effects and for objects changing other objects, that’s the entire point.
Functional programming is immutable by design*, the idea is that you have little to no side effects in your application, except on the very edge of your application (You have to exert output somehow, that’s a side effect). You generally want every function to accept input, process it somehow, and then return an output, without modifying any of the inputted objects.
* That’s not entirely accurate. Functional encourages immutability, and there are functional languages which enforce the no-side-effects rule, but you can produce side effects in functional style programming.
Personally, I like the functional style more, I keep my objects immutable or as immutable as possible. I can guarantee that if I have
var obj = {hello: 'world'};
At the end of the scope, obj
would still be {hello: 'world'}
, regardless of what functions it was passed into. None of the functions modified it along the way.
TL;DR – There’s no clear best practice here. It’s OK to have side effects, as long as you’re aware of the risks of things changing under your feet.
0