Today I Learned - Rocky Kev

TIL functions should only do one thing

POSTED ON:

TAGS:

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.

Via Clean Code Javascript


Related TILs

Tagged:

TIL not obsessively trying to be DRY

Quite often, DRY is applied to any duplication, rather than specifically to the duplication of business rules and knowledge. This is often made worse by automated code analysis tools, which will often highlight any duplication as a code smell.

TIL ways to organize eventListeners

Some code spaghetti I made recently was creating a lot of eventListeners for multiple buttons, and then forgot what they all connected to.

TIL Very Efficient Code

This is a great solution. Easy to understand. Executes really fast. No real-time string concatenation. No over-engineering. String appearance is easily customized.