More Readable Alternatives To Boolean Function Parameters

Boolean function parameters are hard to read. What could true possibly mean here?

settings.createSetting("userAge", true)

You need to look up the function definition to understand this code. The second parameter says where the setting should be stored.

createSetting: function(name, storeInLocalStorage) {}

What can you do to make this easier to read?

This example is based on the Chrome DevTools source code, where they have an elegant solution to this problem.

Instead of passing in a boolean parameter they've introduced a new function with a meaningful name. This function then calls through to the original createSetting method.

createLocalSetting: function(name){
    this.createSetting(name, true)
}

Now, when you read the code that creates the setting, it's clearer what's going on:

settings.createLocalSetting("userAge")

Using An Options Object

Options Objects are another way to explain what arguments are passed into a function, and save the reader from looking up the function definition.

Here's what the createSetting call would look like using an options object:

settings.createSetting({
    name: "userAge",
    storeInLocalStorage: true
})

As you can see, the downside of options objects is that they make code a bit more verbose.

Get an email with a new articles once a week.