Designing Function Signatures You Will Not Regret

A function signature is the part of a library that is hardest to change later. Once people have written thousands of calls against it, every reordered argument or new required parameter is a major release. So the moment of writing the first version is the cheapest time to get it right. Here are the rules I follow, with the reasoning behind each.

Positional for the obvious, an options object for the rest

My default is one or two positional arguments for the things every call needs, followed by an optional options object for everything else.

// Illustrative
resize(image, { width: 800, fit: "contain", background: "#fff" });

// rather than
resize(image, 800, undefined, "contain", "#fff");

The options object has three advantages. Calls are self-describing, because every value has a name next to it. New options can be added in a minor release without disturbing existing calls. And callers can omit anything they do not care about, instead of passing undefined placeholders. Python gets the same benefits from keyword-only arguments, declared after a bare *:

def resize(image, *, width=None, height=None, fit="contain"):
    ...

Avoid bare boolean parameters

A call like save(doc, true, false) is unreadable at the call site. Nobody can tell what the two booleans mean without opening the documentation. I either move them into the options object, or replace a boolean with a small set of named string values, which also leaves room for a third option later. { mode: "overwrite" } can grow to include "append"; overwrite: true cannot grow at all.

Defaults are part of the contract

Changing a default value is one of the sneakiest breaking changes, because the signature looks identical before and after. If timeout defaulted to thirty seconds and now defaults to five, callers who relied on the default will see different behaviour without changing a line. I document every default next to the option, and I treat changing one as a major change unless it is clearly a bug fix.

Leave room to grow

A few habits keep future changes compatible:

A quick review checklist

  1. Can a reader understand a typical call without the docs?
  2. Can I add an option next year without a major release?
  3. Are all defaults written down?
  4. Does every positional argument genuinely appear in every call?

Four questions, asked once, save a great deal of deprecation work later. The post on designing errors covers the other half of a function's contract.

← Back to Home

Subscribe to Our Newsletter

Get the latest updates delivered to your inbox.