assertArgumentType – test expected data types against actual data types

My colleague Andrew Beeching gets credit for this one. An amazingly useful piece of code to check that parameters you are receiving match your expectations. It also allows for null values to be passed, where you might be checking arguments that may or may not exist. It uses jQuery to check for parameters that might be functions and this functionality could be fallible as demonstrated in this article from DHTML Kitchen.

This is especially useful for TDD.

function assertArgumentType(expected, actual, allowNull){
        if (expected !== undefined) {
            actual = actual || null;
        }
        if (expected === Function) {
            if (!$.isFunction(actual)) {
                throw "InvalidArgNotAFunctionException";
            }
            // Match OR object is allowed to be null
        }
        else
            if ((allowNull && actual === null) || (actual.constructor && actual.constructor === expected)) {
                return;
            }
            else {
                switch (expected) {
                    case String:
                        throw ("InvalidArgNotAStringException");
                        break;
                    case Number:
                        throw ("InvalidArgNaNException");
                        break;
                    case Boolean:
                        throw ("InvalidArgNotABooleanException");
                        break;
                    case Array:
                        throw ("InvalidArgNotAnArrayException");
                        break;
                    case Object:
                        throw ("InvalidArgNotAnObjectException");
                        break;
                    case undefined:
                        throw ("InvalidArgUndefinedException");
                        break;
                    case null:
                        throw ("InvalidArgNullException");
                        break;
                }
            }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>