I hereby decree

by David LeMieux

 

There is a pattern in some JavaScript libraries in which methods called on an object return that same object so that more methods can be called. This is known as method chaining and it looks something like this:

$('#myDiv').show().addClass('foo').append("Hello"); //And so on 

This code gets the #myDiv jQuery object, shows it, adds the class 'foo' to it, then appends some HTML. We could continue doing this for many more methods.

Unfortunately, not every method follows this pattern consistently. Setting dimensions, for example:
$('#myDiv').width(300).height(300);

works fine, but if we call either of those methods without the new dimension:
$('#myDiv').width() //Returns a number

what we are really asking for is the current width and so a number is returned. That means we have one method with different return types. The jQuery team have decided this is how they want their interface to work and that is fine but this is something to consider when designing your own library. You could easily imagine that the method should always return the current dimension, even if a new one is set. Perhaps a different method that always return self would then also provide the kind of usability that is desired for chaining (e.g. $().setDimension()).

Method chaining is useful, but so are well defined, consistent interfaces. Promises use this pattern to great effect which is a small part of what makes them so powerful. My own personal preference would be that if your interface method can consistently return self and it would be useful to do so, then make it happen. Otherwise, I fall slightly over the line of being more interested in a clean api.

 

blog comments powered by Disqus