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?
The first rule of functions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Functions should hardly ever be 20 lines long.
Ideally, one line of code is a unit element that means or performs something specific – a part of a sentence if you will. It is generally agreed that the ideal length for a line of code is from 80 to 100 characters.
In order to help keep methods easy to understand they should be no more than 20 lines of code. This does not include whitespace, closing braces, or comments. If a method gets much longer than 20 lines of code then it is either the algorithm is too convoluted or the method is trying too to do to much.
A function should be small because it is easier to know what the function does. How small is small? There should rarely be more than 20 lines of code in one function.
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:
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, lines of code are a bad metric for pretty much anything. It is only a helpful indicator that can potentially point to the real issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With