I find myself writing a lot of functions whereby the first few lines "verify" the arguments, that is, they typecast, check falseness, range, etc. before doing any work. The main reasoning for this is to prevent idiots—human or otherwise—from passing invalid or illogical arguments to the function. An example in JS would be this:
function mix(red, grn, blu, anotherColor) {
// typecast, falseness/presence
this.red = +red || 0
this.grn = +red || 0
this.blu = +red || 0
// args must be within [0, 255]
this.red = Math.max(0, Math.min(red, 255))
this.grn = Math.max(0, Math.min(grn, 255))
this.blu = Math.max(0, Math.min(blu, 255))
// if anotherColor is falsy/undefined
anotherColor = anotherColor || {red:0, grn:0, blu:0}
// do the actual work here
}
Another example is when a recursive function calls itself.
function menulist(pages, depth) {
// do some stuff
// when done, recurse
if (depth > 0) {
// verify pages.sub exists
pages.sub = pages.sub || []
return menulist(pages.sub, depth-1)
}
}
On the other hand I've heard the opinion that this "verification" shouldn't be done within the function itself, rather, it should be delegated to some other piece of the software. In other words, the function should be "pure" and minimal, assuming the arguments passed will be correct. (If this is the case, where should the verification process be delegated?)
Which opinion is considered best practice in the Javascript community, and/or in the programming community as a whole?