Posts Tagged ‘leaky abstraction’

Is it jQuery’s fault it has leaky abstractions?

March 25, 2010

Yes and no.


No its not their fault it has a leaky abstraction.

An example of jQuery not being responsible is here:

    $('#content').css('border');

This is due to several things. One is that different browsers give different result. Two, a border actually consists of four sides (top, bottom, left, and right), and lastly each border side has three properties (style, width, and color). WOW, just looking at a border really includes TWELVE pieces of information.

The only responsibility I see that the implementation .css should return undefined instead of just returning whatever the browser implementation returns. It should force you to select for a very specific border side and property (opinionated software):

    $('#content').css("border-left-style")

Yes it is their fault it has a leaky abstraction.

An example:

    $('#content').addClass('outline');

That’s perfectly good semantics for adding classes to a selector. I say you’re right, but where it breaks down is if you need to add more than one class to a selector. you end up with this:

    $('#content').addClass('outline');
    $('#content').addClass('left_position');
    $('#content').addClass('reset_left');

or you could do this:

    $('#content').addClass('outline').addClass('left_position').addClass('reset_left');

Yawner, everybody understands method chaining. But isn’t one of the powerful tools of jQuery, is the iteration function .each. Shouldn’t we have something like this:

    $('#content').addClasses('outline left_position reset_left');

Let jQuery parse the string into an array of classes and apply it to selector.

And here is how you extend jQuery:

    jQuery.fn.addClasses = function(cssClasses) { 
        // function logic for adding
        // individual classes to selector
    }  
    $('#content').addClasses('outline left_position reset_left');

See: Adding Functions to jQuery


But hey they are only at revision 1.4.2

And those leaky abstractions can be overcome with some extension or changes in behavior. Overall even with the leaky abstractions jQuery is very powerful and useful. I recommend it for everybody.