Sep 25

Simplifying the API of your JS methods

Posted in Javascript      Comments Off on 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, 
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:

            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.