How to help your users out as a library designer

Seems my functional posts have been generating an obscene amount of traffic lately (thank you, Reg). In which spirit, here’s a little suggestion for anyone designing a JavaScript library.

I was reading about Oliver Steele’s MIT-licensed Functional library earlier, and came across this little gem (modified slightly to my whims):

/**
 * Returns a function identical to this function except that
 * it prints its arguments on entry and its return value on exit.
 * This is useful for debugging function-level programs.
 */
Function.prototype.traced = function(name, logger) {
    var self = this, name = name || this, logger = logger || 'info';
    return function() {
        window.console && console[logger](name,
                'called on', this, 'with', arguments);
        var result = self.apply(this, arguments);
        window.console && console[logger](name, '->', result);
        return result;
    }
}

To which I say, never mind function-level programs (though there’s a voice in my ear whispering something about learning Haskell). It’s useful for debugging just about anything. There’s nothing stopping you using this with procedural code or class-based OO programs.

var jibber = {
    age: 68,
    getAge: function(n) {
        return "It's, er... " + (this.age/n) + ". I think.";
    }.traced('getAge()')
};

jibber.getAge(2);

// console prints...
// getAge() called on Object age=68 with [2]
// getAge() -> It's, er... 34. I think.

So we see that we can use it to log method calls, not just bare functions. And it’s not even just useful for debugging. As a library author, you could use it to log interesting points in your codebase, or to highlight upcoming changes to an API in a future release:

MyClass.prototype.jibber = function() {
    return this.wobble.apply(this, arguments);
}.traced('DEPRECATED: use wobble() instead. jibber()', 'warn');

So, before releasing version 2.0 of your library, you could put out a 1.5.x release that just added a bunch of deprecation messages to make it easier for your users to upgrade from 1.5 to 2.0.