I’ve always been taught that having side-effects in an if
condition are bad. What I mean is;
if (conditionThenHandle()) {
// do effectively nothing
}
… as opposed to;
if (condition()) {
handle();
}
… and I understand that, and my collegues are happy because I don’t do it, and we all go home at 17:00 on a Friday and everyone has a merry weekend.
Now, ECMAScript5 introduced methods like every()
and some()
to Array
, and I find them very useful. They’re cleaner than for (;;;)
‘s, give you another scope, and make the element accessible by a variable.
However when validating input, I more-often-than-not find myself using every
/some
in the condition to validate the input, then use every
/some
again in the body to convert the input into a usable model;
if (input.every(function (that) {
return typeof that === "number";
})) {
input.every(function (that) {
// Model.findById(that); etc
}
} else {
return;
}
… when what I want to be doing is;
if (!input.every(function (that) {
var res = typeof that === "number";
if (res) {
// Model.findById(that); etc.
}
return res;
})) {
return;
}
… which gives me side-effects in an if
, condition, which is bad.
In comparison, this is the code would look with with an old for (;;;)
;
for (var i=0;i<input.length;i++) {
var curr = input[i];
if (typeof curr === "number") {
return;
}
// Model.findById(curr); etc.
}
My questions are:
- Is this definitely a bad practice?
- Am I (mis|ab)using
some
andevery
(should I be using afor(;;;)
for this?) - Is there a better approach?
8
If I understand your point correctly, you seem to be mis-using or abusing every
and some
but it’s a little unavoidable if you want to change the elements of your arrays directly. Correct me if I’m wrong, but what you’re trying to do is find out if some or every element in your sequence exhibits a certain condition then modify those elements. Also, your code seems to be applying something to all items until you find one that doesn’t pass the predicate and I don’t think that’s what you mean to be doing. Anyways.
Let’s take your first example (slightly modified)
if (input.every(function (that) {
return typeof that === "number";
})) {
input.every(function (that) {
that.foo();
}
} else {
return;
}
What you’re doing here actually goes a little against the spirit of the some/every/map/reduce/filter/etc concepts. Every
isn’t meant to be used to affect every item that conforms to something, rather it should only be used to tell you if every item in a collection does. If you want to apply a function to all items for which a predicate evaluates to true, the “good” way to do it is
var filtered = array.filter(function(item) {
return typeof item === "number";
});
var mapped = filtered.map(function(item) {
return item.foo(); //provided foo() has no side effects and returns a new object of item's type instead. See note about foreach below.
});
Alternatively, you could use foreach
instead of map to modify the items in-place.
The same logic applies to some
, basically:
- You use
every
to test if all elements in an array pass some test. - You use
some
to test if at least one element in an array passes some
test. - You use
map
to return a new array containing 1 element (which
is the result of a function of your choice) for every element in an
input array. - You use
filter
to return an array of length 0 <length
<initial array length
elements, all contained in the original array and all
passing the supplied predicate test. - You use
foreach
if you want map but in-place - You use
reduce
if you want to combine the results of an array in a single object result (which could be an array but doesn’t have to).
The more you use them (and the more you write LISP code), the more you realize how they are related and how it’s even possible to emulate/implement one with the others. What’s powerful with these queries and what’s really interesting is their semantics, and how they really push you towards eliminating harmful side-effects in your code.
EDIT (in light of comments):
So let’s say you want to validate that every element is an object and convert them to an Application Model if they’re all valid. One way to do this in a single pass would be:
var dirty = false;
var app_domain_objects = input.map(function(item) {
if(validate(item)) {
return new Model(item);
} else {
dirty = true; //dirty is captured by the function passed to map, but you know that :)
}
});
if(dirty) {
//your validation test failed, do w/e you need to
} else {
//You can use app_domain_objects
}
This way, when an object doesn’t pass validation, you still keep iterating through the entire array, which would be slower than just validating with every
. However, most of the time your array will be valid (or I should hope so), so in most cases you’ll perform a single pass over your array and end up with a usable array of Application Model objects. Semantics will be respected, side-effects avoided and everyone will be happy!
Note that you could also write your own query, similar to foreach, which would apply a function to all members of an array and returns true/false if they all pass a predicate test. Something like:
function apply_to_every(arr, predicate, func) {
var passed = true;
for(var i = 0; i < array.length; ++i) {
if(predicate(arr[i])) {
func(arr[i]);
} else {
passed = false;
break;
}
}
return passed;
}
Although that would modify the array in place.
I hope this helps, it was very fun to write. Cheers!
4
The side effects are not in the if condition, they are in the if’s body. You have only determined whether or not to execute that body in the actual condition. There is nothing wrong with your approach here.
2