// Keeps functions small, focused, and doing one thing well
# Small Functions
Functions should be small and do one thing well.
## The Rule
- Functions should be small (ideally < 20 lines)
- They should do one thing
- They should do it well
- They should do it only
## Bad Example
```javascript
function processOrder(order) {
// Validate
if (!order.items || order.items.length === 0) {
throw new Error("No items");
}
// Calculate total
let total = 0;
for (const item of order.items) {
total += item.price * item.quantity;
}
// Apply discount
if (order.coupon) {
total *= 0.9;
}
// Save to database
db.orders.insert(order);
// Send email
sendEmail(order.customer.email, "Order confirmed");
return total;
}
```
## Good Example
```javascript
function processOrder(order) {
validateOrder(order);
const total = calculateOrderTotal(order);
saveOrder(order);
notifyCustomer(order);
return total;
}
function validateOrder(order) {
if (!order.items?.length) {
throw new Error("No items");
}
}
function calculateOrderTotal(order) {
const subtotal = calculateSubtotal(order.items);
return applyDiscount(subtotal, order.coupon);
}
function calculateSubtotal(items) {
return items.reduce((sum, item) =>
sum + item.price * item.quantity, 0
);
}
```
## Benefits
- Easier to understand
- Easier to test
- Easier to reuse
- Easier to modify
- Self-documenting code6 matches