Why build a program from small functions?
Why one big do-everything function is worse than ten small ones.
1. A small function can be checked on its own. deliveryCost(999) → 300, deliveryCost(1000) → 0 — and it's all clear. One huge function can only be checked as a whole, and you can't tell which part went wrong.
const deliveryCost = (total) => (total >= 1000 ? 0 : 300);
console.log(deliveryCost(999));
console.log(deliveryCost(1000));Now compare it with a monolith. Here's the do-everything function from my first shop, just very short. A customer complains: they ordered $1000 worth and were charged $1300.
function checkout(cart, code) {
let total = 0;
for (const item of cart) total += item.price * item.qty;
if (code === "FISH") total = total - total / 10;
if (total > 1000) total += 0;
else total += 300;
return total;
}
console.log(checkout([{ price: 1000, qty: 1 }], "FISH"));
console.log(checkout([{ price: 1000, qty: 1 }], ""));A program cut into parts can be questioned one suspect at a time:
const cartTotal = (cart) => cart.reduce((sum, item) => sum + item.price * item.qty, 0);
const applyPromo = (total, code) => (code === "FISH" ? total - total / 10 : total);
const deliveryCost = (total) => (total > 1000 ? 0 : 300);
console.log(cartTotal([{ price: 1000, qty: 1 }]));
console.log(applyPromo(1000, ""));
console.log(deliveryCost(1000));> instead of >=.2. A name explains the code. applyPromo(cartTotal(cart), code) reads like a sentence. Inside a big function, the same steps are anonymous lines, and you have to guess what each one means.
3. Parts can be reused. cartTotal is needed in the cart badge, at checkout and in the receipt email. One function — one place where the total is computed correctly (or wrongly, but then the same everywhere, and someone notices fast).
4. Changes stay local. New delivery rules mean editing one three-line function, not searching the whole program.
5. No surprises from outside. A good small function gets everything it needs through parameters and returns a result without changing anything outside. Such functions are called pure: the same arguments always give the same answer. Here's what happens when a function peeks at a shared variable:
let discount = 0;
function finalPrice(price) {
return price - discount;
}
console.log(finalPrice(500));
discount = 100; // somewhere at the other end of the program, a sale was switched on
console.log(finalPrice(500));A pure function can be called in a test, in the console, in another project — it behaves the same everywhere. If the price needs a discount, let it come in as a parameter: finalPrice(500, discount). Then the call shows everything the answer depends on.
Myth or fact?
Decide whether the statement is true. Got it wrong? Try again; once you're right, Byte explains what's going on.