4 ms·
I agree, but also I think this is misrepresenting the 'early return' pattern. It's more likely to be succinct and look like this instead: function check(x)
by tpoacher 6y ago
I agree, but also I think this is misrepresenting the 'early return' pattern. It's more likely to be succinct and look like this instead:
function check(x) {
if (!test1 (x)) return false;
if (!test2 (x)) return false;
if (!test3 (x)) return false;
if (!test4 (x)) return false;
return true;
}
In _this_ scenario, it is true that this is much more readable than:
function check(x) {
if (!test1 (x)) {
return false;
} else if (!test2 (x)) {
return false;
} else if (!test3 (x)) {
return false;
} else if (!test4 (x)) {
return false;
} else {
return true;
}
}
- brundolf 6y agoWorth noting that elses don't require curly braces, which are where most of the visual noise is coming from in your example: function check(x) { if (!test1 (x)) return false; else if (!test2 (x)) return false; else if (!test3 (x)) return false; else if (!test4 (x)) return false; else return true; } I think this is more clear than either of the above
- tsimionescu 6y agoNever ever use if without curly braces. That's one of the worst ideas of C's syntax. Your first example would still look clean like this: function check(x) { if (!test1 (x)) { return false; } if (!test2 (x)) { return false; } if (!test3 (x)) { return false; } if (!test4 (x)) { return false; } return true; } And it would be much safer from stupid copy/paste errors.
- jhgb 6y agoInstead of function check(x) { if (!test1 (x)) return false; if (!test2 (x)) return false; if (!test3 (x)) return false; if (!test4 (x)) return false; return true; } why wouldn't you do something along the lines of (every (lambda (f) (funcall f x)) (list #'test1 #'test2 #'test3 #'test4a)) or whatever is the equivalent in your preferred language?
- wvenable 6y agoThe tests are rarely that simple or regular.
- jhgb 6y agoIsn't that exactly the reason to put them somewhere else?
- wvenable 6y agoNo, I just mean the actual tests might be something like: if (user == null) return false; if (IsCompleted(user)) return true; if (action == null) return false; if (value < 0 || value > 100) return false; You're not usually just passing a single value to a bunch of "test" functions.
- jhgb 6y agoWell, the way it was written, I was assuming that conditions to be satisfied had separate named predicates (although combinators could alleviate even some of these things).
- alerighi 6y agoThat code is ugly anyway, something I would have wrote in middle school... why not: function check(x) { return test1(x) && test2(x) && test3(x) && test4(x); } Or, since I assume is JavaScript, just: const check = x => test1(x) && test2(x) && test3(x) && test4(x);
- brundolf 6y agoNobody would actually write this, it's just a demonstration of the pattern at hand for the sake of discussion