2 ms·
You're sort of coming at this backwards. What you want to avoid is side-effects. One class of side-effect would be database operations. So let's imagine you
by Lazare 11y ago
You're sort of coming at this backwards.
What you want to avoid is side-effects. One class of side-effect would be database operations. So let's imagine you have this code:
let products = [{id: 1, price: 10.12, desc: 'foo'}, {id: 2, price: 5, desc: 'bar'}];
for (i = 0; i < products.length; i++) {
products[i] = formatPrice(products[i]);
}
console.log(products);
Looks good, right? I mean, presumably formatPrice just, I dunno, turns prices from numbers into strings like "$5.00", or whatever. But what if formatPrice looked like this?
function formatPrice(product) {
product.desc = '';
saveToDatabase(product);
product.price = '$' + product.price.toString();
return product;
}
There might be some reason why that's the exact functionality you want, but it's terrible practice to write; your price formatting code is performing database operations, which are side effects. Don't do that. :)
What you want is to chain together a number of simple functions. And sure, one of them could even be "saveToDatabase". That's fine. What's not fine is having some random function, somewhere, randomly mutating your database.
If you think FP requires you not to use a database, you've badly misunderstood FP. What it's asking is for you to be explicit about what you're doing. Pure functions are easy to reason about; global variables are hard. Database operations are especially hard to reason about, which is why you want them locked away safely at the start and end of your processing chain, and not just as random side effects of otherwise unrelated code.