# Thread: average function length...

1. ## average function length...

How long is the average function? I remember being told to keep the program modular and the length of functions relatively short. This is usually ok but I still find myself sometimes writing functions whcih are nearly 100 lines long. So I guess the question is how long is too long?

2. That depends on what the function is supposed to do!

3. Function length, like program length, is a matter of program design. You can have a 1000 lines function or a hundred 10 lines functions.

Kuphryn

4. The material you have probably read was talking about keeping your code readable and modular. I agree with that completely. Keep them as small as can be easily read and understood.

If the question of callstack speed comes up...

Yes, calling more functions can slow things down a tad. But not if they are inline. Pick out repetitive functions that are in areas where you should optimize and add the inline keyword. This will allow the readability of a modular function without the speed loss.

5. In a 100 line function, I think it's pretty likely there is some common functionality that can be factored out into smaller functions which are called more than once. Instead of one 100 line function, perhaps it's possible to break it into a 50 line function and a 30 line function that is called twice.

6. Stolen from Code Complete -

...if you think it makes sense to make a certain routine 100, 150, or 200 lines long, it's probably all right to do so. Current evidence says that routines of such length are no more error prone than shorter routines and are likely to be cheaper to develop.

If you want to write routines longer than about 200 lines, be careful.

...In a study of the code for IBM's OS/360 operating system and other systems, the most error prone routines were larger than 500 lines of code. Beyond 500 lines, the error rate tended to be proportional to the size of the routine.

etc
However, as others have pointed out, you may have more reasons for breaking up a program than preventing errors.

7. The reason I have this function is that it initialises a class object from the user input. The reason its about 180 lines is because there are about 7 variables to initialise and some conversions to enumerations that I'm using switch statments for.

Time for stripping it down a bit into smaller functions, theres lots of yes/no questions which could be changed

Thanks for all the advice

Popular pages Recent additions