Skip to content

Instantly share code, notes, and snippets.

@dexygen-gistio
Last active December 22, 2015 01:59
Show Gist options
  • Save dexygen-gistio/6400266 to your computer and use it in GitHub Desktop.
Save dexygen-gistio/6400266 to your computer and use it in GitHub Desktop.
The death knell for if/else/switch

Turning once more to the outstanding underscore.js library -- see also http://gist.io/6376616 -- it turns out that with concerted effort you can do away with if/else statements. Consider for instance the following interface composed of (pun intended) _.compose and _.wrap

_.compose(submitForm, _.wrap(unlessFormInvalid, showFormErrors))();

If you can get past the noisiness of the actual invocation of underscore functions, and perhaps an aversion to Perl and/or it's 'unless' keyword, the above statement would be hard-pressed to better describe it's intentions, and furthermore lends itself to exclaiming: "Look Ma, No if/else!" However, I personally don't like the aforementioned noise, particularly if it were to be coupled with any necessary 'this.' prefixes, not to mention such an approach would not easily scale to support conditions besides the (implicit) 'if', and 'else'.

Enter "promises", "thennables": whatever you want to call them. And you don't need a library, such as whatever's been forked off of node.js; rather the following should be trivial to implement with standard Javascript tools such as closures:

this.validateForm().then({
    onValid: this.submitForm,
    onInvalid: this.showFormErrors
});

Trivial to extend when you have more conditions than just on/off, so that not only can you relegate if/else to the dust-bin of computer science history, but 'switch' to boot


Dexygen: Software, Simple and Powerful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment