Ask HN: Maximum length within a control structure

2 points by danvesma ↗ HN
Pip pip good hackers,

I'm just starting a new project and I think there's a good chance that someone else will end up maintaining the code. I'm looking at setting myself some readability rules regarding the way that the code is put together.

One of the worst bits of untangling my own old spaghetti code is my dreadful habit of enclosing many many lines of code within my control structure. Sometimes an IF can start, and the ELSE not follow for two or three hundred lines.

Where would you draw the line? My thinking is that if I can't see the whole IF...ELSE, SWITCH, FOR or WHILE in a single screen height (75 lines in Coda for me), that it needs refactoring.

Really interested to hear what standards you work with yourselves,

Cheers,

Dan http://beset.me

2 comments

[ 8.4 ms ] story [ 13.0 ms ] thread
I would say that if you can't fit a function onto your screen, it's too long and should be broken up.
According to Robert C. Martins book "Clean Code", and the SLAP principle, the maximum length of a method (yes, an entire method) is around 20 - 50 lines of code. If it gets longer than that, odds are that it is doing more than one thing and is operating on different levels of abstraction, and should be broken up into smaller methods. I would also say that I have rarely seen (if ever) well-written, easy to comprehend and maintain code where the control structures and methods contain hundreds of lines of code.