How Long Should a Function Be? Practical Limits and How to Split Long Methods (video)

There is no magic number, but long functions are harder to read, test, and change. See practical limits teams use, signs a function does too much, and step-by-step refactoring with Extract Method.

Read the full article

Transcript

How Long Should a Function Be? Practical Limits and How to Split Long Methods. Here's the short version.

Ask ten developers how long a function should be and you get ten numbers. The number matters less than the reason behind it: a function should do one thing that you can name, read in one sitting, and test on its own.

Practical limits. Most functions in healthy codebases are short: often under 20 lines. Around 50 to 70 lines is where most teams and tools start warning. Past 100 lines, a function almost always does several jobs. Treat the limit as a prompt to look, not a hard rule; a long switch over a fixed set of cases can be fine.

Here's an example: Validation, pricing, persistence and email in one place.

Signs a function does too much. You need comments like "// step 2: validate" to explain sections. The name has "and" in it, or is vague (Process, Handle, DoWork). It has several levels of nesting. Changing one behaviour risks breaking another in the same function.

How to split safely. First, make sure tests cover the current behaviour (add a few if they do not). Second, pick a block that does one thing and extract it into a function with a clear name. Third, pass in only what the block needs and return its result. Fourth, run the tests, commit, and repeat with the next block.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos