Expands on Handling required parameters in ECMAScript 6 by Axel Rauschmayer.
The idea (which is credited to Allen Wirfs-Brock) is, in essence, to use default parameter values to call a function which throws an Error if the parameter is missing:
const throwIfMissing () => { throw new Error('Missing parameter') }
const foo = (mustBeProvided = throwIfMissing()) => {}
foo() // ==> Error: Missing parameter
This idea is great. However, the Error message does not tell you which parameter is missing, which could be quite helpful if the function had multiple parameters or an option object with multiple options, for example. To give more accurate Error feedback, we could refactor the code as follows:
const throwIfMissing = p => { throw new Error(`Missing parameter: ${p}`) }
const foo = (mustBeProvided = throwIfMissing('mustBeProvided')) => {}
foo() // ==> Error: Missing parameter: mustBeProvided
Now, the code for such a seemingly simple task, enforcing that a parameter is required, has become quite long, however: minus the parameter name, throwIfMissing('')
is 18 characters long.
Since this is such a fundamental and often used task, it makes sense to make it as short and easy-to-type as possible.
If we use template literal syntax foo´string´
for calling the function instead of the normal round brackets syntax foo('string')
, we can already reduce the number of characters by 2.
const throwIfMissing = p => { throw new Error(`Missing parameter: ${p}`) }
const foo = (mustBeProvided = throwIfMissing`mustBeProvided`) => {}
foo() // ==> Error: Missing parameter: mustBeProvided
Nevertheless, it is still 16 characters long, excluding the parameter name, of course. Now, the only option left to reduce the number of characters needed for this simple task is to rename the throwIfMissing
function.
There are quite a few shorter alternatives which I like, for example:
throwIfNo
(e.g.throwIfNo´password´
)enforce
(e.g.enforce´password´
)ensure
(e.g.ensure´password´
)
My favorite, however, is just x
. Why an x
?
- Well, the
x
represents a check mark:[x]
. - It's also super short. Now, we're from 18 characters down to 3 (plus the parameter name).
Before:
const throwIfMissing () => { throw new Error('Missing parameter') }
const foo = (mustBeProvided = throwIfMissing()) => {}
foo() // ==> Error: Missing parameter
After:
const x = p => { throw new Error(`Missing parameter: ${p}`) }
const foo = (mustBeProvided = x`mustBeProvided`) => {}
foo() // ==> Error: Missing parameter: mustBeProvided
Simple "real world" example using throw-if-missing
:
const x = require('throw-if-missing')
const login = ({ username = x`username`, password = x`password` } = {}) => {}
login({ username: 'C-3PO' }) // ==> Error: Missing password
Very good for the more explicit error message, but I don't think we gain much from the conciseness of x versus throwIfmissing. We are sacrificing readability here and intuitiveness for pure character gains and nothing else IMO