TIL functions should only do one thing
POSTED ON:
TAGS: cleancode javascript
The most important rule of programming is - break your code into tiny bite-sized pieces. That makes it easier to compose, test, and add it.
Bad:
function emailClients(clients) {
clients.forEach(client => {
const clientRecord = database.lookup(client);
if (clientRecord.isActive()) {
email(client);
}
});
}
Good:
function emailActiveClients(clients) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {
const clientRecord = database.lookup(client);
return clientRecord.isActive();
}
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
clients.filter(isActiveClient)
fires that callback function isActiveClient
, passing in the clients
array into it, and then returns only the successful ones.
Then, it runs the forEach(email);
to finally send a email to those in that new array.
In a future update, if your boss considers all Active Clients to have the tag 'active' in the database, then that can be quickly updated in the isActiveClient()
function you created.
Related TILs
Tagged: cleancode