Script Valley
Writing Clean Code: Naming, Functions & Structure
Writing Functions That Do One ThingLesson 2.2

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

Function length zones

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.

Up next

How many parameters should a function take

Sign in to track progress

How long should a function be โ€” the right answer โ€” Writing Functions That Do One Thing โ€” Writing Clean Code: Naming, Functions & Structure โ€” Script Valley โ€” Script Valley