German Attanasio
German Attanasio

Reputation: 23653

Using callbacks with optional parameters

I've seen libraries taking advantages of optional parameters and callbacks when writing functions. I'm writing a library, and I would like to know if it is a good practice to allow the user to skip the optional parameters and just send the callback.

For example:

function listFiles(params, callback) {
  if (typeof params === 'function' && !callback) {
    callback = params;
    params = {};
  }
  // more code here...
}

Users of my library can call listFiles() with parameters:

listFiles({ verbose: true }, function callback(err, results) { /*... */ })

or passing only the callback() function:

listFiles(function callback(err, results) { /*... */ })

The main benefit I see with this approach is that users won't have to do:

listFiles(null, function callback(err, results) { /*... */ })

or

listFiles({}, function callback(err, results) { /*... */ })

The problem is that if I make verbose a required parameter I will be breaking users that were not sending params along with the ones that were sending empty or null as params.

Should I use optional parameters as a callback or is this a bad idea?

Upvotes: 1

Views: 350

Answers (1)

Rob Johansen
Rob Johansen

Reputation: 5164

Why not make callback one of the params so users always pass a single argument to listFiles()?

function listFiles(params) {
    // ... check for optional params and do something with them
    params.callback(err, result);
}

Now as a user I can pass the optional params if I want (using limit and sort as examples):

listFiles({
    limit: 10,
    sort: 'desc',
    callback: (err, result) => {
        // ... do something with result
    }
});

Or just the required callback param if I want to allow listFiles() to provide defaults for me:

listFiles({
    callback: (err, result) => {
        // ... do something with result
    }
});

Upvotes: 2

Related Questions