Multiple arguments vs. options object

Like many of the others, I often prefer passing an options object to a function instead of passing a long list of parameters, but it really depends on the exact context.

I use code readability as the litmus test.

For instance, if I have this function call:

checkStringLength(inputStr, 10);

I think that code is quite readable the way it is and passing individual parameters is just fine.

On the other hand, there are functions with calls like this:

initiateTransferProtocol("http", false, 150, 90, null, true, 18);

Completely unreadable unless you do some research. On the other hand, this code reads well:

initiateTransferProtocol({
  "protocol": "http",
  "sync":      false,
  "delayBetweenRetries": 150,
  "randomVarianceBetweenRetries": 90,
  "retryCallback": null,
  "log": true,
  "maxRetries": 18
 });

It is more of an art than a science, but if I had to name rules of thumb:

Use an options parameter if:

  • You have more than four parameters
  • Any of the parameters are optional
  • You’ve ever had to look up the function to figure out what parameters it takes
  • If someone ever tries to strangle you while screaming “ARRRRRG!”

Leave a Comment