Skip to content

Instantly share code, notes, and snippets.

@kyleshevlin
Created September 20, 2019 05:15
Show Gist options
  • Save kyleshevlin/be89540633427d5b3d8b5ed3a54cd696 to your computer and use it in GitHub Desktop.
Save kyleshevlin/be89540633427d5b3d8b5ed3a54cd696 to your computer and use it in GitHub Desktop.
Flag arguments, boo! pt 1
// I think boolean arguments maybe kind of suck. I'm still making up my mind on this,
// but let me show you why I'm leaning the way I am.
// I have a function that fills out a form and optionally submits it.
// Maybe this is a function you'd use in a test suite or something similar.
function fillOutForm(values, submit = true) {
// Do some stuff with the values
if (submit) {
form.submit()
}
}
// Now let's use it.
fillOutForm({ name: 'Kyle', email: 'kyle@exmaple.com' })
fillOutForm({ name: 'Anna', email: 'anna@example.com' }, false)
// The problem with the boolean flag is that it conveys no information at the call site.
// If this is an imported function and I see an argument that is only optionally added,
// I have to go all the way to the function definition (or docs) to figure out what it means.
// Sure, we do that all the time, but maybe it's a bit better to do something more verbose like this
const defaultOptions = {
submit: true
}
function fillOutForm(values, options = defaultOptions) {
// Do some stuff with the values
const { submit } = options
if (submit) {
form.submit()
}
}
// Now the call sites give us a bit more information when we deny submission
fillOutForm({ name: 'Kyle', email: 'kyle@exmaple.com' })
fillOutForm({ name: 'Anna', email: 'anna@example.com' }, { submit: false })
// What do you think?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment