How to name a function which calls callback if certain conditions are met?
Problem
I recently started working with nodejs. I'd like to follow the async nature of it and write some helper functions which take one function as an argument and call that function only if certain criteria are met, for example:
function areMandatoryFieldsFilledOut( fields, httpRequest, httpResponse, callback ) {
/* some logic */
if( mandatory_fields_have_been_filled_out ) {
callback();
} else {
httpResponse.send('Mandatory fields have not been filled out!');
}
}
// usage
areMandatoryFieldsFilledOut(['username', 'password'], req, res, function () {
// this is executed only if both username and password values are supplied
}
What would be the best way write such functions? Is there a special word that You use for the beginning of the function name, like, 'ensure', e.g. 'ensureAuthenticated( callback )
?'
Is there a way to convince the reader of my code that the callback will be called only if the criteria are met just by function declaration (name and args)?
Solution
The existing nomenclature for this thing includes the connect
/express
name of middleware
or the Ruby on Rails
name of a before_filter
. I use express middleware which has a very similar pattern but coupled with an ordered stack
of functions, in which case I name these functions without any specific convention other than trying to be clear about what they do, check for, or require.
app.post('/submit', signedIn, authorized, formIsValid, function (req, res) { /*...code to process form.../*});
Sometimes I tack a MW
on to the end if I want to make it clear this is middleware like parseFormMW
or supportedFormatMW
.
Discussion
View additional discussion.