Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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:

  1. Is this definitely a bad practice?
  2. Am I (mis|ab)using some and every (should I be using a for(;;;) for this?)
  3. Is there a better approach?
share|improve this question
2  
Every and some as well as filter,map, and reduce are queries, they have no side effects, if they do you're abusing them. –  Benjamin Gruenbaum Feb 9 '13 at 20:40
    
@BenjaminGruenbaum: So doesn't that make them toothless more often than not? 9/10, if I use some, I want to do something with the element, if I use every, I want to do something to all of those elements... some and every don't let me access that information, so either I can't use them, or I have to add side-effects. –  Isaac Feb 9 '13 at 20:45
    
No. When I refer to side effects I mean inside the head of the if not the body. Inside the body you can modify it any way you'd like. Just don't mutate the object inside the callback you pass to some/when. –  Benjamin Gruenbaum Feb 9 '13 at 21:01
    
@BenjaminGruenbaum: But that's exactly my point. If I use some in my if condition to determine whether a certain element in the array exhibits a certain property, 9/10 I need to operate on that element in my if body; now, as some doesn't tell me which of the elements exhibited the property (just "one did"), I can either use some again in the body (O(2n)), or I can just perform the operation inside the if condition (which is bad, because its a side-effect within the head). –  Isaac Feb 9 '13 at 21:07
    
... the same applies for every as well, of course. –  Isaac Feb 9 '13 at 21:07
show 3 more comments

2 Answers

up vote 4 down vote accepted

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!

share|improve this answer
    
Thanks for your answer. I'm not necessarily trying to modify the elements in place per-se; in my actual code, I'm receiving a JSON-formatted array of objects, so I'm first validating the input if (input.every()), to check that each element is an object (typeof el === "object && el !== null) etc, then if that validates, I want to convert each element into the respective Application Model (which, now you mention map() I could use input.map(function (el) { return new Model(el); });; but not necessarily in place. –  Isaac Feb 10 '13 at 11:03
    
.. but see that even with map() I'm having to iterate over the array twice; once to validate, and another to convert. However, using a standard for(;;;) loop, I could do this using one iteration, but I can't find a way to apply every, some, map or filter in this scenario, and perform only one pass, without having undesired-side-effects or otherwise introducing bad-practice. –  Isaac Feb 10 '13 at 11:06
    
@Isaac Alright, sorry for the delay, I understand your situation more clearly now. I'll edit my answer to add some stuff. –  pwny Feb 11 '13 at 0:59
    
Thanks for the great answer; it's been really helpful :). –  Isaac Feb 11 '13 at 10:58
add comment

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.

share|improve this answer
    
Hi, thanks for your answer. Sorry, but either I've misunderstood your answer, or you've misinterpreted the code... everything in my code snippet is within the if condition, with only the return being inside the if's body; obviously I'm talking about the code sample preceeded by "what want to be doing is;... –  Isaac Feb 9 '13 at 20:30
1  
Sorry, @Issac's side effects are indeed in the if condition. –  Ross Patterson Feb 9 '13 at 22:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.