Function Length and Single Responsibility
You'll learn why keeping functions short and focused makes your code more readable, testable, and maintainable.
The Core Principle
A function should be short and do one thing well. When a function tries to handle multiple responsibilities or operates at different levels of abstraction, it becomes harder to understand, test, and modify. Think of a restaurant kitchen: you wouldn't want one chef simultaneously chopping vegetables, grilling steaks, and baking desserts. Each station handles one specific task.
Why Short Functions Matter
Short functions (typically 10-20 lines, sometimes fewer) are easier to:
- Understand at a glance – You grasp what it does without scrolling
- Name accurately – Clear purpose leads to clear names
- Test thoroughly – Fewer branches mean simpler test cases
- Reuse – Single-purpose functions fit more scenarios
One Thing, One Level
A function does "one thing" when you can't meaningfully extract another function from it without simply restating its implementation. Additionally, all statements should operate at the same level of abstraction.
Bad example (mixed abstraction levels):
validateUser(userData):
if userData.email contains "@":
query database for user
if user exists:
hash password with SHA-256
compare hashes
Better approach (consistent abstraction):
validateUser(userData):
if isValidEmail(userData.email):
return authenticateAgainstDatabase(userData)
Each function now handles one responsibility at one abstraction level. validateUser orchestrates high-level logic, while isValidEmail and authenticateAgainstDatabase handle specific tasks.
The Analogy
Think of functions as paragraphs in a well-written essay. Each paragraph conveys one main idea with supporting details at a consistent level of specificity. You wouldn't mix philosophical arguments with technical implementation details in the same paragraph.
Key Takeaway: Keep functions short (10-20 lines), focused on a single responsibility, and operating at one level of abstraction—this makes your code easier to read, test, and maintain.