views:

114

answers:

3

Please consider the following function body:

var isValidated = true;
$(selector1).each(function(){
    //do validation with local f()...
    isValidated = f() && isValidated;
});

$(selector2).each(function(){
    //do validation with local f()...
    isValidated = f() && isValidated;
});

$(selector3).each(function(){
    //do validation with local f()...
    isValidated = f() && isValidated;
});

return isValidated;

My description of the progress of isValidated is Boolean concatenation---but there has to be an official, computer-science term for this thing. What is it? To clarify, the idea here is to let each $() block run---but when any one of these blocks have a validation failure the results of this failure must return false over all blocks (true && true && false == false). So, like many programmers, I am using some kind of a pattern but we often don't know what it is called. So does this pattern resemble anything useful?

+10  A: 

Boolean Logic. (and look at the "chaining operations" section).

Traveling Tech Guy
+1 for George Boole!
Ben S
Also of interest: Short-circuit evaluation: http://en.wikipedia.org/wiki/Short-circuit_evaluation
Ben S
Okay: so this could also be called *Boolean chaining*...
rasx
+2  A: 

Not sure if this is a named pattern per se, but I just wanted to point out a minor observation... Since you are just returning boolean, it would be better to switch your checks so that after the first failure the logic will simply short circuit as false without running additional functions unnecessarily:

isValidated = isValidated  && f();

The only reason to ensure you still run every f() is if they are doing something like marking UI fields with errors for the user. If they are simply validating, no need to run them once the outer check is false.

bmoeskau
@bmoeskau you are correct: every f() must run for marking UI fields...
rasx
if your functions are both performing the validation and marking the UI, they're doing too many things. Those are separate concerns.
rmeador
+1  A: 

I'm assuming from your use of .each() that you also have access to an .inject() function, which is what I'd recommend using when you're building a single value from an enumerable.

function validated(a) {
  return a.inject(true, function(acc, el){ return(acc && f()); });
}

return validated($(selector1)) && validated($(selector2)) && validated($(selector3));
Matt Gillooly
@mattgillooly.com: I like your approach here because it avoids sharing a variable like `isValidated` among different functions...
rasx