Simplifying the API of your JS methods

If you’ve been using JavaScript for some time, I’m positive that you’ve seen JS methods which look like this:

function doSomething(address, 
methodName,
shouldThrowOnError,
successCb,
errorCb) { //code goes here }

In my opinion, this kind of API sucks. If you’re not seeing why, then suppose that all parameters are optional. When you only need to set the first parameter, things aren’t really that hard. Now, suppose you want to set the last parameter…with the previous API, you’ll need to pass default values for all the parameters and that really sucks, right? With the current API,here’s the code you’d need for setting only the last paragraph:

doSomething(null,null,
            null,
            null,
            function(err) {
                //handle error here
            });

Fortunately, there’s an easy way to solve this mess: we can use literal objects to “aggregate” the function’s parameters. Here’s the refactored API:

function doSomething(options) {
    //code goes here
    //access options.address here for address, etc.
}
doSomething( {
        errorCb: function(err) {
            //handle error here
        }
});

As you can see, we need to change the API so that it expects an object which “aggregates” all the method parameters. The advantage of using this technique is that, now, consumers of your API can specify only the parameters that need to be set. This is really a simple change which makes life easy for the consumers of your library. In my opinion, you should use whenever possible. And that’s it for today.

Advertisements

~ by Luis Abreu on September 25, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: