Say we have a function, createUser
, which requires four arguments in order to create a new user (by calling some API).
When looking at the function signature itself, things seem to make pretty good sense. But how about when we call it?
It’s pretty unclear what the arguments mean, right? Especially the last two booleans. I would have to go to the implementation to look it up. Instead, we can wrap the arguments in an object.
Thanks to ES6 object destructuring, we can do this easily by simply adding curly brackets around the arguments. Now, whenever we call createUser
, we pass an object as a single argument with the required values as properties instead.
See how nice that reads out now. We’re no longer in doubt what those booleans mean. There’s another version of this that I’ve seen very often: Passing optional arguments as an options
object. The idea is to pass 1-2 essential arguments and then pass the remaining arguments as an options
object.
Now we need to check if the options
object is set before accessing its values and provide proper fallbacks. On the other hand, calling the createUser
function now looks very clean.
The first two arguments are pretty obvious, and we can now optionally provide options when needed.
0 comments:
Post a Comment