How long should a function be โ the right answer
function length guidelines, indentation depth, scroll-free functions, line count heuristics, cognitive complexity
Function Length: How Long Is Too Long
There's no single correct line count. But there are strong signals that a function has grown past its natural size.
The scroll test: if you have to scroll to read the entire function in your editor, it's too long. Your working memory degrades as you scroll. The entire function should fit on one screen โ roughly 20-30 lines maximum.
The indentation test: count the levels of indentation. More than two levels (a loop inside a condition, for example) is a sign the function is doing too much.
// Three levels deep โ extract something
function processOrders(orders) {
for (const order of orders) { // level 1
if (order.status === 'pending') { // level 2
if (order.items.length > 0) { // level 3
// now doing work
}
}
}
}Extract the innermost logic:
function hasPendingItems(order) {
return order.status === 'pending' && order.items.length > 0;
}
function processOrders(orders) {
for (const order of orders) {
if (hasPendingItems(order)) {
processOrder(order);
}
}
}Aim for 5-15 lines per function as a healthy default. Functions shorter than five lines are often fine โ don't add padding. Functions longer than 20 lines need scrutiny but aren't automatically wrong.
The real metric is cognitive complexity: how much do you have to hold in your head while reading this function? If the answer is "a lot," the function is too long regardless of its line count.
