How many lines of code should a function/procedure/method have?

Alex Angas picture Alex Angas · Mar 4, 2009 · Viewed 44.7k times · Source

Possible Duplicate:
When is a function too long?

I've recently been given the unenviable task of reviewing poor code written by another developer and documenting the bad practices. (This is all for the purposes of getting out of paying for the developer's work rather than any altruistic reason, of course!)

The reviewed code has several procedures that are many lines of code - the longest is almost 600 lines. A couple of problems with this that I've thought of are maintainability and readability.

The trick is that I need to justify to a layperson why this is a bad practice and if possible back it up with a well regarded and current reference book. Analogies are good too.

Any ideas?

Duplicate: When is a function too long?
Duplicate: Best rule for maximum function size?

Answer

Rex M picture Rex M · Mar 4, 2009

It's not about lines of code. As Steve Mcconnell and Bob Martin say (two pretty good references on coding best practices), a method should do one thing and only one thing. However many lines of code it takes to do that one thing is how many lines it should have. If that "one thing" can be broken into smaller things, each of those should have a method.

Good clues your method is doing more than one thing:

  • More than one level of indention in a method (indicates too many logic branches to only be doing one thing)
  • "Paragraph Breaks" - whitespace between logical groups of code indicate the method is doing more than one thing

Just to name a few. Bob Martin also says to keep it around 10. Personally I usually try to shoot for 10. If it starts getting close to 20, that's a mental flag to pay closer attention to that method. But ultimately, LoC is a bad metric for pretty much anything. It is only a helpful indicator that can potentially point to the real issue.