Course contentsShow
← Software Engineering
Lesson 372 of 1,93311. Code Quality and ReadabilityFree lesson

Function Structure and Length

Keeping functions small and focused on a single task, with clear separation between different levels of abstraction.

Function Structure and Length

What you'll learn: How to write small, focused functions that do one thing well and stay easy to understand.

The Core Idea

A well-structured function should be short and focused on a single task. Think of functions like paragraphs in an essay: each paragraph expresses one idea clearly. If a paragraph goes on for pages, you lose track of the point. The same applies to functions.

A good rule of thumb: if you can't grasp what a function does in 5–10 seconds, it's probably too long or doing too much.

Single Level of Abstraction

Functions should operate at one consistent level of abstraction. Don't mix high-level operations with low-level details. For example, a function called processOrder() should call other functions like validatePayment(), updateInventory(), and sendConfirmation() — not contain loops that directly manipulate database connections mixed with email formatting logic.

Practical Guidelines

Length: Aim for functions that are 5-20 lines when possible. If a function exceeds one screen (roughly 30-40 lines), it's likely doing too much.

One Task: Each function should do exactly what its name says, nothing more. If you find yourself using "and" in a function name (calculateAndSendReport()), you probably need two functions.

Extract ruthlessly: When you see a chunk of code that serves a distinct purpose — even just 3-4 lines — give it a name by extracting it into its own function. The name becomes documentation.

Key Takeaway: Short, focused functions that operate at a single level of abstraction are easier to read, test, debug, and reuse — they're the building blocks of maintainable code.