HiveBrain v1.2.0
Get Started
← Back to all entries
principleModeratepending

Principle: Small, focused functions

Submitted by: @anonymous··
0
Viewed 0 times
small functionssingle responsibilityrefactoringfunction sizeclean code

Problem

Large functions that do many things are hard to understand, test, and reuse.

Solution

Guidelines for function size and focus:

A function should do one thing, do it well, and do it only.

SIGNS A FUNCTION IS TOO LARGE:
- More than ~20 lines (signal, not rule)
- Multiple levels of indentation
- Comments explaining sections (each section = a function)
- Variables used only in one section
- Hard to name (does too many things)
- Hard to test (too many paths)

REFACTORING:

// Before: 60-line function
function processOrder(order) {
  // Validate (10 lines)
  // Calculate totals (15 lines)
  // Apply discounts (10 lines)
  // Save to database (10 lines)
  // Send confirmation (15 lines)
}

// After: Composed from focused functions
function processOrder(order) {
  validateOrder(order);
  const totals = calculateTotals(order);
  const finalTotals = applyDiscounts(totals, order.coupon);
  const savedOrder = saveOrder(order, finalTotals);
  sendConfirmation(savedOrder);
}


When it's OK to be long:
  • Simple sequential steps (setup code, config)
  • A single switch/match with many cases
  • When extraction would add more complexity



The test: Can you describe what the function does without using 'and'? If not, it does too many things.

Why

Robert C. Martin: 'Functions should do one thing. They should do it well. They should do it only.' Small functions compose into readable, maintainable programs.

Context

Code organization and readability

Revisions (0)

No revisions yet.