Created
September 20, 2019 05:15
-
-
Save kyleshevlin/be89540633427d5b3d8b5ed3a54cd696 to your computer and use it in GitHub Desktop.
Flag arguments, boo! pt 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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: '[email protected]' }) | |
fillOutForm({ name: 'Anna', email: '[email protected]' }, 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: '[email protected]' }) | |
fillOutForm({ name: 'Anna', email: '[email protected]' }, { submit: false }) | |
// What do you think? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment