May 21, 2008
Type enforcement and argument validation in JavaScript saves time
Debugging JavaScript is hard enough - but it is especially annoying when you have spent a good amount of time tracking down a bug and it turns out to be a type error (i.e., your function expected a Boolean true but got a String “true”). Perhaps your value was implicitly cast to another type by some operation, or maybe you forgot to pass the right arguments to a method. In a statically-typed, compiled language (such as AS3 or Java), you would find out about bad arguments during compile time - and you’d probably get a nice, descriptive error message of what was going on. Not so with JavaScript - in fact, because it is loosely and dynamically typed, you may not find out about your bad argument until you waste an hour or two tracking down a bug.
To avoid this sort of thing, you can throw your own errors when a method or constructor doesn’t get what it expects. The pattern is easy to get the hang of. The very first time you get one of these errors, you will feel good about all this extra typing.
/**
* A function that creates a new barf bag.
* @param {Boolean} zip Whether this bag has a zipper or not.
* @param {String} bagType Valid types: "paper"|"plastic"
* @param {String} vomitType Valid types: "chunky"|"bile"|"watery"
*/
var VomitBag = function(zip, bagType, vomitType) {
/* validate arguments */
if(typeof zip != "boolean") throw new Error("VomitBag: expected zip to be Boolean");
if(typeof bagType != "string" || !(/^paper$|^plastic$/.test(bagType)) throw new Error("VomitBag: expected bagType to be String and to be either 'paper' or 'plastic'");
if(typeof vomitType != "string" || !(/^chunky$|^bile$|^watery$/.test(vomitType)) throw new Error("VomitBag: expected vomitType to be String and to be 'chunky', 'bile', or 'watery'");
/* some code... */
}
This technique is not at all new to JavaScript. For example, Marijn Haverbeke talks about it briefly during a good writeup about error handling in Eloquent JavaScript: Error Handling - Eloquent JavaScript (that whole site is worth reading).