Course contentsShow
← C
Lesson 1200 of 1,21916. Practice and ProjectsFree lesson

Limiting function length and complexity

Limiting function length and complexity

What you'll learn: How to write cleaner, more maintainable code by keeping your functions small and focused on a single task.

The "One Page" Rule

Imagine reading a recipe book where a single instruction for "Making Dinner" lasts forty pages. You would lose your place, forget the ingredients, and struggle to find where the salt goes. Programming is no different.

In professional C development, a good rule of thumb is that a function should fit on a single screen—roughly 20 to 40 lines. If you have to scroll down to see the end of a function, it is likely doing too much. When a function grows too long, it becomes a "God Function," an all-powerful block of code that is nearly impossible to debug because one small change in line 10 might break something invisible on line 200.

Lowering Cognitive Load

Complexity isn't just about length; it’s about "indentation depth." Every time you add an if statement inside a for loop inside another if statement, you are forcing the next programmer to hold a massive mental map of conditions just to understand one line of code.

Professional style favors "early exits." Instead of nesting your entire logic inside a giant if block, check for errors at the top and return immediately. This keeps the main logic at the lowest level of indentation.

Example: Refactoring for Clarity

Compare these two approaches to processing a sensor reading:

// POOR STYLE: Deep nesting and multiple responsibilities
void process_data(int sensor_val) {
    if (sensor_val > 0) {
        if (sensor_val < 100) {
            // Imagine 50 lines of math here...
            printf("Value is within safe operating range.\n");
        } else {
            printf("Error: Overheating!\n");
        }
    } else {
        printf("Error: No signal.\n");
    }
}

// PROFESSIONAL STYLE: Small, flat, and focused
void handle_error(int val) {
    if (val <= 0) printf("Error: No signal.\n");
    if (val >= 100) printf("Error: Overheating!\n");
}

void process_data_clean(int sensor_val) {
    if (sensor_val <= 0 || sensor_val >= 100) {
        handle_error(sensor_val);
        return; // Early exit
    }

    // Main logic stays at the "top level"
    printf("Value is within safe operating range.\n");
}

By breaking the error handling into its own function, the main logic becomes a straight line rather than a maze.

Key takeaway

Small functions are easier to test, easier to name, and significantly easier for your future self to read.