Ask HN: Functions: how long is too long?
First I was going to ask how long you think a function should be, but there are lots of cases where using short functions is convenient.
Instead I'd like to ask what's the longest you'll let a function get in a given language before you break it up? Why?
I have very little experience coding commercially, but I try and never let any function get >1 screenfull, which is 50 lines for me.
12 comments
[ 3.7 ms ] story [ 38.8 ms ] threadI do, however, find that it is essential to limit the width of functions, and if my code doesn't comfortably fit into 80 columns when using 8-column tabs, there's a clear sign that it needs to be broken up.
In general, nested loops are far more of a problem than simple "do X, then do Y, then do Z" code.
Sure. main() in http://www.freebsd.org/cgi/cvsweb.cgi/src/usr.sbin/portsnap/... is over 400 lines long, and it
* Looks up a server's DNS entries,
* Connects to the server (trying multiple addresses if necessary),
* Constructs HTTP requests and sends them to the server,
* If less than one HTTP request is pending, blocks until it can finish writing a request,
* Reads HTTP response headers,
* Reads an HTTP response body and writes the data to disk,
* Prints a status line,
* if the server sent an HTTP/1.1 response, loops back to the top to continue sending more requests and reading more responses using the same TCP connection,
* and if the connection broke, closes it and loops back to the top to open a new connection and continue downloading.
I separated out the bits which could usefully be put into their own functions (e.g., constructing an HTTP request, or reading a \r\n terminated line from a socket), but there was no point dividing up the rest.
That, and once you get into the hundred+ lines of code, you are probably doing something that's more easily summed up as a couple pieces. Using multiple pieces also has the advantage of it being very easy to rapidly change / experiment with your code.
That's a pretty good indicator because it shows that you could 'abstract' something out and make it an individual routine.
Err on the side of caution, better to have smaller functions than larger ones, unless you have a very good reason not to.
And if performance is your worry and you work in 'C' then inline is your friend.
7 +- 2
not including declaratons