Saturday, October 30, 2010

JavaScript, Closures, and Wasteful API's

First, read this function: later (YUI). I consider this a great example of how framework developers can overreach with abstractions, considering that JavaScript has lexical scope and closures that are fairly easily implemented. Now, read the implementation: YUI-Later.js

Yahoo has written roughly 30 lines to encapsulate and abstract the simple functionality of passing a thunk to either setInterval or setTimeout. An example, stripped from Todd Kloots' YUI 3 demo:
var args = [ 1,2 ]
Y.later( 50, gizmo, gizmo.foo, args )

Could be more simply expressed as:
setTimeout( 50, function( ){ gizmo.foo( 1, 2 ) } )

And, hey look, no CDN callout required. No need for a code reviewer to reach out for YUI's documentation to find out the special semantics of YUI, and it explains exactly what it means. And, bonus, fewer keystrokes.

Libraries like jQuery and YUI have valuable capabilities, such as concealing all of the W3C's pointless DOM verbosity behind more modern XPath-like selectors. But when these frameworks feel the need to abstract away closures, all I really see is a developer who has lost touch with the clear simplicity of JavaScript.. And start wondering if they get paid by the API function.

No comments:

Post a Comment