One line ifs and literate programming
A collegue of mine, Vinicius Gomes, exposes in this blog post reasons to have one line if blocks.
Following up with the discussion he started, I would like to show a technique to apply that concept in a more literate way in JavaScript.
One way to enforce this pratice and end up having more readable code is to extend the JS Function object, adding a behavior that is found in other languages, such as Ruby.
Paraphrasing his example:
function died() {
return tries > 10;
}
function gameOver() {
alert("You lose :(");
}
With these two functions, we would normally write something along the lines of:
if (died()) gameOver();
But we can expand the language and write something like:
gameOver.if(died());
Unfortunatelly “if” is a keyword in JS, so we have to improvise. We can search for suitable alternatives:
gameOver.when(died()); gameOver.givenThat(died());
I don’t really like the “when” word, since it could mean the scheduling of a task, but for now it’s the shortest implementation I could think of without recurring to “_if”.
Implementing this is quite simple:
Function.prototype.when = function(bool) {
if (bool) return this();
}
Or the shorter way:
Function.prototype.when = function(bool) {
return bool ? this() : undefined;
}
Following this line of thinking we can also easily implement “unless”:
Function.prototype.unless = function(bool) {
return !bool ? this() : undefined;
}
But what if our function has parameters?
We can do this:
var validateContactForm = function() {
return validate($('#contactForm'));
}
validateContactForm.when(validationIsEnabled);
Or the shorter way using function currying:
var validateContactForm = validate.curry($('#contactForm'));
validateContactForm.when(validationIsEnabled);
What are your thoughts about this?
October 15th, 2010 at 23:12
Hi Filipe – I like your approach.
I usually do this, which I find quite elegant:
died() && gameOver();
Also you might be interested in my blog on a similar topic:
http://javascriptweblog.wordpress.com/2010/07/26/no-more-ifs-alternatives-to-statement-branching-in-javascript/
October 16th, 2010 at 12:47
@Angus:
Really good post.
I also usually go with && and ||, but that could mess up the return value of the function.