Coding a "defensive" or a "contractual" API is a design decision, if you opt for the defensive way, here is a neat module called have that will help you to have your arguments, and validate it too!
Here is a simple example of two functions straight from the source, that does the same argument validations, the first one is without using have and the second one is with have:
12345678910111213141516171819
functionwithoutHave(id,arr,opts,callback){assert(typeofid==='string'||typeofid==='number','id argument not string or number');if(!(arrinstanceofArray)){arr=[arr];}for(vari=0;i<arr.length;i++){assert(typeofarr[i]==='string','arr member not a string');}if(typeofopts==='function'){callback=opts;opts={x:'some default value'};}assert(!opts||typeofopts==='object','options object not a hash');assert(typeofcallback==='function','callback missing or not a function');// logic...}
12345678910111213141516
functionwithHave(id,arr,opts,callback){have(arguments,{id:'str or num',arr:'str or str array',opts:'optional obj',callback:'func'});if(!(arrinstanceofArray)){arr=[arr];}if(typeofopts==='function'){callback=opts;opts={x:'some default value'};}// logic...}
How's have better than any other argument validator?
assert.js:92
throw new assert.AssertionError({ ^
AssertionError: inside function: test, one argument is not string
at funcName (/private/tmp/k.js:6:3) at ensure (/private/tmp/node_modules/have/have.js:109:5) at have (/private/tmp/node_modules/have/have.js:124:11) at have.one (/private/tmp/k.js:12:5) at test(/private/tmp/k.js:19:3) at Object.<anonymous> (/private/tmp/k.js:22:1) at Module._compile (module.js:456:26) at Object.Module._extensions..js (module.js:474:10) at Module.load (module.js:356:32) at Function.Module._load (module.js:312:12)
GIF FTW!
Thanks to Stdarg for suggesting this module and also a special thanks to chakrit the author of 'have' module